From 742164c6ad27c44255033a79e08a17fc8429b74f Mon Sep 17 00:00:00 2001 From: Anders Eskildsen <22001464+aeskildsen@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:58:38 +0100 Subject: [PATCH 1/5] chore: set up Tailor and just recipes; build with uv_build Set up the repository with Tailor, add the shared `just` recipes and move the build to `uv_build`. - Tailor: `.tailor.yml`, issue templates, `CODE_OF_CONDUCT.md`, `CONTRIBUTING.md`, `SECURITY.md`, `SUPPORT.md` and the `just` files. No Tailor languages: the recipes run the scripts in `just/project/`. - Recipes: `check`, `test` and `build`. `lint` runs `actionlint`. - Build backend: `uv_build` in place of setuptools; `MANIFEST.in` is removed. The package files in the wheel and the sdist are the same as before. The setuptools metadata files and `MANIFEST.in` are gone, and the sdist now has `pyproject.toml.orig`. - `ruff` and `basedpyright` are in the `test` extra. Checked: the tests pass from the unpacked sdist, from an editable install and from a `pip` install. --- .github/ISSUE_TEMPLATE/bug_report.yml | 88 +++++++ .github/ISSUE_TEMPLATE/config.yml | 8 + .github/ISSUE_TEMPLATE/feature_request.yml | 64 +++++ .gitignore | 6 + .tailor.yml | 280 +++++++++++++++++++++ CODE_OF_CONDUCT.md | 91 +++++++ CONTRIBUTING.md | 48 ++++ MANIFEST.in | 4 - SECURITY.md | 17 ++ SUPPORT.md | 34 +++ docs/development.md | 18 +- just/loader.just | 10 + just/project/build.sh | 5 + just/project/test.sh | 8 + just/tailor.just | 109 ++++++++ justfile | 9 + pyproject.toml | 19 +- 17 files changed, 803 insertions(+), 15 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .tailor.yml create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md delete mode 100644 MANIFEST.in create mode 100644 SECURITY.md create mode 100644 SUPPORT.md create mode 100644 just/loader.just create mode 100644 just/project/build.sh create mode 100644 just/project/test.sh create mode 100644 just/tailor.just create mode 100644 justfile diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..58ba1a0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,88 @@ +name: πŸ› Bug Report +description: Report a bug or issue +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + Please fill out the information below to help us diagnose and fix the issue. + + - type: textarea + id: steps + attributes: + label: Steps to Reproduce + description: Steps to reproduce the behavior + placeholder: | + 1. Run command: `...` + 2. Do something else: `...` + 3. Error occurs + validations: + required: true + + - type: textarea + id: expected + attributes: + label: Expected Behavior + description: What you expected to happen + placeholder: Describe the expected outcome + validations: + required: true + + - type: textarea + id: actual + attributes: + label: Actual Behavior + description: What actually happened + placeholder: Describe what actually occurred + validations: + required: true + + - type: textarea + id: error-output + attributes: + label: Error Output + description: Full error message or output (if any) + render: shell + placeholder: Paste the complete error message here + validations: + required: false + + - type: input + id: version + attributes: + label: Version + description: The version or commit hash of this project you are using + placeholder: e.g., 1.0.0, latest main branch, commit abc123def + validations: + required: true + + - type: textarea + id: environment + attributes: + label: Environment + description: Any relevant environment details + placeholder: e.g., operating system, runtime version, browser, container + validations: + required: false + + - type: textarea + id: additional-context + attributes: + label: Additional Context + description: Any other context about the problem + placeholder: Add any other relevant information, screenshots, or context + validations: + required: false + + - type: checkboxes + id: terms + attributes: + label: Checklist + description: Please confirm the following + options: + - label: I have searched existing issues to avoid duplicates + required: true + - label: I have provided all the requested information above + required: true + - label: I can reproduce this issue consistently + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..f92898b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: πŸ›Ÿ Support + url: "https://github.com/aeskildsen/md2misc/blob/HEAD/SUPPORT.md" + about: Check the support guide before opening an issue. +# - name: Code of Conduct Report +# url: https://yourproject.org/community-report/ +# about: Report a Code of Conduct violation privately to the moderation team. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..299ca92 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,64 @@ +name: ✨ Feature Request +description: Suggest a new feature or enhancement +labels: ["enhancement"] +body: + - type: markdown + attributes: + value: | + Please provide details about your idea below. + + - type: textarea + id: problem + attributes: + label: Problem Statement + description: Is your feature request related to a problem? Please describe. + placeholder: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + validations: + required: true + + - type: textarea + id: solution + attributes: + label: Proposed Solution + description: Describe the solution you'd like + placeholder: A clear and concise description of what you want to happen. + validations: + required: true + + - type: textarea + id: alternatives + attributes: + label: Alternatives Considered + description: Describe alternatives you've considered + placeholder: A clear and concise description of any alternative solutions or features you've considered. + validations: + required: false + + - type: textarea + id: use-case + attributes: + label: Use Case + description: Describe your specific use case + placeholder: How would you use this feature? What workflow would it improve? + validations: + required: true + + - type: textarea + id: additional-context + attributes: + label: Additional Context + description: Add any other context about the feature request + placeholder: Add any other context, screenshots, mockups, or examples about the feature request here. + validations: + required: false + + - type: checkboxes + id: terms + attributes: + label: Checklist + description: Please confirm the following + options: + - label: I have searched existing issues to avoid duplicates + required: true + - label: I have considered if this feature fits the project scope + required: true diff --git a/.gitignore b/.gitignore index 35c355a..d5e9c99 100644 --- a/.gitignore +++ b/.gitignore @@ -40,3 +40,9 @@ tests/book-export/ ## virtual environment .venv/ + +## Tailor writes this folder again on each run; this repository has no Nix tooling +/nix/ + +## build output +dist/ diff --git a/.tailor.yml b/.tailor.yml new file mode 100644 index 0000000..59bf1cb --- /dev/null +++ b/.tailor.yml @@ -0,0 +1,280 @@ +license: GPL-3.0 + +languages: + go: false + rust: false + python: false + shell: false + javascript: false + +# Model Context Protocol integrations are opt-in. +mcp: + blender: false + playwright: false + +repository: + description: Regex-based python converter from markdown to miscellaneous formats + homepage: "" + has_wiki: false + has_discussions: false + has_projects: false + has_issues: true + allow_merge_commit: false + allow_squash_merge: true + allow_rebase_merge: false + squash_merge_commit_title: PR_TITLE + squash_merge_commit_message: PR_BODY + delete_branch_on_merge: true + allow_update_branch: true + allow_auto_merge: true + web_commit_signoff_required: false + private_vulnerability_reporting_enabled: true + vulnerability_alerts_enabled: true + automated_security_fixes_enabled: true + default_workflow_permissions: read + can_approve_pull_request_reviews: false + secret_scanning: enabled + secret_scanning_push_protection: enabled + secret_scanning_non_provider_patterns: enabled + +immutable_releases: + enabled: false + +actions: + # Options: all, local_only, selected. SHA pinning applies separately. + # selected requires github_owned_allowed, verified_allowed, and patterns_allowed. + enabled: true + allowed_actions: all + sha_pinning_required: false + fork_pr_contributor_approval: + approval_policy: first_time_contributors + +code_scanning: + state: configured + query_suite: default + threat_model: remote + # An empty list means GitHub detects the languages. Valid values: + # actions, c-cpp, csharp, go, java-kotlin, javascript-typescript, python, ruby, swift + languages: [] + +code_quality: + state: not-configured + # An empty list means GitHub detects the languages. Valid values: + # csharp, go, java-kotlin, javascript-typescript, python, ruby + languages: [] + +ruleset: + # Tailor manages one ruleset named "Tailor" and owns it entirely. + # active enforces the rules. disabled keeps the ruleset on GitHub but + # GitHub ignores it, so a hand-made ruleset can govern instead. + enforcement: active + bypass_actors: + # actor_type: RepositoryRole, Team, User, Integration, DeployKey + # RepositoryRole actor_id: 2 maintain, 4 write, 5 admin + # bypass_mode: always, pull_request, exempt + - actor_id: 5 + actor_type: RepositoryRole + bypass_mode: always + conditions: + ref_name: + # Branch names or fnmatch patterns in refs/heads/ form. + # include also accepts ~DEFAULT_BRANCH and ~ALL. + include: + - ~DEFAULT_BRANCH + exclude: [] + rules: + creation: false + update: false + deletion: true + required_linear_history: false + required_signatures: false + non_fast_forward: true + pull_request: + enabled: true + parameters: + required_approving_review_count: 0 + dismiss_stale_reviews_on_push: true + require_code_owner_review: false + require_last_push_approval: false + required_review_thread_resolution: true + require_extra_approval_for_unattributed_changes: false + # Any combination of merge, squash, rebase. At least one. + allowed_merge_methods: + - squash + required_status_checks: + enabled: false + parameters: + # Require branches to be up to date before merging. + strict_required_status_checks_policy: false + # Do not require status checks on creation. + do_not_enforce_on_create: false + # context is the check name as shown on a pull request. For a GitHub + # Actions job that is the job's name. integration_id is optional and + # restricts the check to one app; 15368 is GitHub Actions. + required_status_checks: [] + code_scanning: + enabled: false + parameters: + # tool is the tool name as GitHub shows it, for example CodeQL. + # alerts_threshold: none, errors, errors_and_warnings, all + # security_alerts_threshold: none, critical, high_or_higher, medium_or_higher, all + code_scanning_tools: + - tool: CodeQL + alerts_threshold: errors + security_alerts_threshold: high_or_higher + +# Pages is opt-in. Omission or enabled: false leaves Pages unmanaged. +# generator: static (default) creates a starter in an empty path. Hugo and Jekyll need an existing site. +# path: project-relative source directory, default pages. +# branch: omit to use the current repository default branch. +# cname: omit to preserve the domain, use "" to clear it, or set a domain. +pages: + enabled: false + generator: static + path: pages + # branch: main + # cname: www.example.com + # Static only. Omit links to leave the page unchanged; {} clears its marked links. + # Use full HTTPS URLs, or a bare address for email. Empty values add no icon. + # links: + # website: https://example.com + # email: hello@example.com + +labels: + - name: bug + color: d20f39 + description: "Something isn't working" + + - name: documentation + color: 04a5e5 + description: Documentation improvement + + - name: duplicate + color: 8839ef + description: Already exists + + - name: enhancement + color: 1e66f5 + description: New feature request + + - name: good first issue + color: 40a02b + description: Good for newcomers + + - name: help wanted + color: "179299" + description: Extra attention needed + + - name: invalid + color: e64553 + description: Not valid or relevant + + - name: question + color: 7287fd + description: Needs more information + + - name: wontfix + color: dc8a78 + description: Will not be worked on + + - name: dependencies + color: fe640b + description: Dependency update + + - name: github_actions + color: ea76cb + description: GitHub Actions update + + - name: hacktoberfest-accepted + color: df8e1d + description: Hacktoberfest contribution + +# Repository Actions variables are non-secret values. +# Tailor creates or updates only declared variables and leaves others unchanged. +# variables: +# - name: DEPLOY_REGION +# value: "eu-west-2" +# - name: RELEASE_SUFFIX +# value: "" + +swatches: + - path: .github/dependabot.yml + alteration: never + + - path: .github/FUNDING.yml + alteration: never + + - path: .github/ISSUE_TEMPLATE/bug_report.yml + alteration: first-fit + + - path: .github/ISSUE_TEMPLATE/feature_request.yml + alteration: first-fit + + - path: .github/ISSUE_TEMPLATE/config.yml + alteration: first-fit + + - path: .github/pull_request_template.md + alteration: never + + - path: SECURITY.md + alteration: first-fit + + - path: CODE_OF_CONDUCT.md + alteration: first-fit + + - path: CONTRIBUTING.md + alteration: first-fit + + - path: SUPPORT.md + alteration: first-fit + + - path: justfile + alteration: first-fit + + - path: flake.nix + alteration: never + + - path: .gitignore + alteration: first-fit + + - path: .envrc + alteration: never + + - path: cubic.yaml + alteration: never + + - path: .github/workflows/tailor-pages.yml + alteration: first-fit + + - path: pages/index.html + alteration: first-fit + + - path: pages/style.css + alteration: first-fit + + - path: pages/theme.js + alteration: first-fit + + - path: pages/icon.svg + alteration: first-fit + + - path: wiki/Home.md + alteration: first-fit + + - path: wiki/_Sidebar.md + alteration: first-fit + + - path: wiki/_Footer.md + alteration: first-fit + + - path: .github/workflows/tailor-wiki.yml + alteration: first-fit + + - path: .tailor.yml + alteration: always + + - path: ruff.toml + alteration: first-fit + + - path: pyrightconfig.json + alteration: first-fit diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..123612d --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,91 @@ +# Contributor Covenant 3.0 Code of Conduct + +## Our Pledge + +We pledge to make our community welcoming, safe, and equitable for all. + +We are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, color, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant. + + +## Encouraged Behaviors + +While acknowledging differences in social norms, we all strive to meet our community's expectations for positive behavior. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language. + +With these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including: + +1. Respecting the **purpose of our community**, our activities, and our ways of gathering. +2. Engaging **kindly and honestly** with others. +3. Respecting **different viewpoints** and experiences. +4. **Taking responsibility** for our actions and contributions. +5. Gracefully giving and accepting **constructive feedback**. +6. Committing to **repairing harm** when it occurs. +7. Behaving in other ways that promote and sustain the **well-being of our community**. + + +## Restricted Behaviors + +We agree to restrict the following behaviors in our community. Instances, threats, and promotion of these behaviors are violations of this Code of Conduct. + +1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop. +2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people. +3. **Stereotyping or discrimination.** Characterizing anyone’s personality or behavior on the basis of immutable identities or traits. +4. **Sexualization.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community. +5. **Violating confidentiality**. Sharing or acting on someone's personal or private information without their permission. +6. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group. +7. Behaving in other ways that **threaten the well-being** of our community. + +### Other Restrictions + +1. **Misleading identity.** Impersonating someone else for any reason, or pretending to be someone else to evade enforcement actions. +2. **Failing to credit sources.** Not properly crediting the sources of content you contribute. +3. **Promotional materials**. Sharing marketing or other commercial content in a way that is outside the norms of the community. +4. **Irresponsible communication.** Failing to responsibly present content which includes, links or describes any other restricted behaviors. + + +## Reporting an Issue + +Tensions can occur between community members even when they are trying their best to collaborate. Not every conflict represents a code of conduct violation, and this Code of Conduct reinforces encouraged behaviors and norms that can help avoid conflicts and minimize harm. + +When an incident does occur, it is important to report it promptly. To report a possible violation, use the contact details available in the project's repository. + +Community Moderators take reports of violations seriously and will make every effort to respond in a timely manner. They will investigate all reports of code of conduct violations, reviewing messages, logs, and recordings, or interviewing witnesses and other participants. Community Moderators will keep investigation and enforcement actions as transparent as possible while prioritizing safety and confidentiality. In order to honor these values, enforcement actions are carried out in private with the involved parties, but communicating to the whole community may be part of a mutually agreed upon resolution. + + +## Addressing and Repairing Harm + +These remedies and repairs are guidelines for this project's code of conduct enforcement process. + +If an investigation by the Community Moderators finds that this Code of Conduct has been violated, the following enforcement ladder may be used to determine how best to repair harm, based on the incident's impact on the individuals involved and the community as a whole. Depending on the severity of a violation, lower rungs on the ladder may be skipped. + +1) Warning + 1) Event: A violation involving a single incident or series of incidents. + 2) Consequence: A private, written warning from the Community Moderators. + 3) Repair: Examples of repair include a private written apology, acknowledgement of responsibility, and seeking clarification on expectations. +2) Temporarily Limited Activities + 1) Event: A repeated incidence of a violation that previously resulted in a warning, or the first incidence of a more serious violation. + 2) Consequence: A private, written warning with a time-limited cooldown period designed to underscore the seriousness of the situation and give the community members involved time to process the incident. The cooldown period may be limited to particular communication channels or interactions with particular community members. + 3) Repair: Examples of repair may include making an apology, using the cooldown period to reflect on actions and impact, and being thoughtful about re-entering community spaces after the period is over. +3) Temporary Suspension + 1) Event: A pattern of repeated violation which the Community Moderators have tried to address with warnings, or a single serious violation. + 2) Consequence: A private written warning with conditions for return from suspension. In general, temporary suspensions give the person being suspended time to reflect upon their behavior and possible corrective actions. + 3) Repair: Examples of repair include respecting the spirit of the suspension, meeting the specified conditions for return, and being thoughtful about how to reintegrate with the community when the suspension is lifted. +4) Permanent Ban + 1) Event: A pattern of repeated code of conduct violations that other steps on the ladder have failed to resolve, or a violation so serious that the Community Moderators determine there is no way to keep the community safe with this person as a member. + 2) Consequence: Access to all community spaces, tools, and communication channels is removed. In general, permanent bans should be rarely used, should have strong reasoning behind them, and should only be resorted to if working through other remedies has failed to change the behavior. + 3) Repair: There is no possible repair in cases of this severity. + +This enforcement ladder is intended as a guideline. It does not limit the ability of Community Managers to use their discretion and judgment, in keeping with the best interests of our community. + + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public or other spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 3.0, permanently available at [https://www.contributor-covenant.org/version/3/0/](https://www.contributor-covenant.org/version/3/0/). + +Contributor Covenant is stewarded by the Organization for Ethical Source and licensed under CC BY-SA 4.0. To view a copy of this license, visit [https://creativecommons.org/licenses/by-sa/4.0/](https://creativecommons.org/licenses/by-sa/4.0/) + +For answers to common questions about Contributor Covenant, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are provided at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). Additional enforcement and community guideline resources can be found at [https://www.contributor-covenant.org/resources](https://www.contributor-covenant.org/resources). The enforcement ladder was inspired by the work of [Mozilla’s code of conduct team](https://github.com/mozilla/inclusion). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b2e5433 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,48 @@ +# Contributing + +Contributions are welcome. Read the [issue and pull request rules](#issue-and-pull-request-rules) before you write code. + +- **Report bugs and request features** in [Issues](../../issues) +- Commit messages must conform to the [Conventional Commits](https://www.conventionalcommits.org/) specification +- All contributors are expected to follow the [Code of Conduct](CODE_OF_CONDUCT.md) +- Security issues must be reported privately; see [SECURITY.md](SECURITY.md) +- By contributing, you confirm that you have the right to license your contribution under the project [licence](LICENSE) + +## This repository + +- [docs/development.md](docs/development.md) tells you how to set up the environment, run the tests and make a release. +- The TeX fixtures in `tests/fixtures` are the output of `md2tex` and the reference for the TeX backend. Change them only if the TeX output is meant to change. + +## Issue and pull request rules + +Maintainers close issues and pull requests that break these rules without review. To try again, fix the cause and open a new one. + +### 1. Complete the template + +Every issue and pull request must use its template, with every section completed. Do not delete sections or leave placeholder text. + +### 2. Open an issue before a new feature + +A pull request that adds a feature or enhancement must resolve an issue that a maintainer accepted before you started work. Link it in the description, for example `Closes #123`. Bug fixes and documentation changes do not need an issue. Maintainers decide whether a change is a feature. + +### 3. One change per pull request + +A pull request must contain one bug fix, one documentation change, or one feature. Do not bundle several changes. Send each one as a separate pull request. + +### 4. No unsolicited rewrites + +Do not rewrite, restructure, or reformat existing code unless a maintainer agreed to it in an issue. + +Maintainers and automated dependency updates are exempt from these rules. + +## AI-assisted contributions + +You may use AI assistance for code, documentation, and GitHub communication. Every contribution must have a responsible person in the loop who reviews and understands it before submission and remains accountable for it. + +- AI-assisted contributions must meet the same project standards as other contributions. +- Check AI-assisted material for licence and attribution requirements before submission. +- AI tools may assist reviews, but a person must make the final decision. +- Answer questions about your contribution and respond to feedback yourself, without relaying messages between reviewers and AI tools. +- Do not add an AI identity to `Signed-off-by` or `Co-authored-by` trailers. `Signed-off-by` is a commit trailer for a person who makes the stated certification. +- You may disclose material AI assistance with an `Assisted-by:` trailer, for example `Assisted-by: tool:model`. +- Routine tools for grammar, spelling, or language clarity do not need disclosure. diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index 9a7cf08..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,4 +0,0 @@ -# The sdist has the complete test setup: the tests, their helper modules and -# the fixtures. tests/fixtures/ATTRIBUTION.md gives the licence of the fixtures. -graft tests -global-exclude __pycache__ *.py[cod] diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..821b877 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,17 @@ +# Security Policy + +## Supported Versions + +Only the latest release is supported. Security fixes are released as patch versions. + +## Reporting a Vulnerability + +**Do not open a public issue for security vulnerabilities.** + +[Report vulnerabilities privately](https://github.com/aeskildsen/md2misc/security/advisories/new). Include: + +- Steps to reproduce +- Affected versions +- Potential impact + +This project is maintained on a best-efforts basis. There are no guaranteed response times for security reports. diff --git a/SUPPORT.md b/SUPPORT.md new file mode 100644 index 0000000..e124b64 --- /dev/null +++ b/SUPPORT.md @@ -0,0 +1,34 @@ +# Support + +## Getting Help + +Before opening an issue, check the existing resources: + +- **[README](../../#readme)** for installation, usage, and configuration +- **[Open issues](../../issues)** for known bugs and planned features +- **[Closed issues](../../issues?q=is%3Aissue+is%3Aclosed)** for previously resolved problems +- **[Discussions](../../discussions)** for questions and community help, if enabled + +## Reporting Bugs + +Use the [bug report template](../../issues/new?template=bug_report.yml) and include: + +- Steps to reproduce +- Expected and actual behaviour +- Version and environment details + +To fix a bug yourself, see [CONTRIBUTING.md](CONTRIBUTING.md). + +## Requesting Features + +Use the [feature request template](../../issues/new?template=feature_request.yml) and describe: + +- The problem you are trying to solve +- Your proposed solution +- Your specific use case + +## What to Expect + +- This project is maintained on a best-efforts basis. +- There are no guaranteed response times or support SLAs. +- Security issues should be reported privately per [SECURITY.md](SECURITY.md). diff --git a/docs/development.md b/docs/development.md index 80a7711..fef958a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,5 +1,19 @@ # Development +## Recipes + +The [`just`](https://just.systems) recipes run the common tasks. Activate the virtual environment, or keep it in `.venv`. + +| Recipe | What it runs | +|---|---| +| `just check` | `just test` | +| `just test` | all tests (`pytest`) | +| `just lint` | `actionlint` | +| `just build` | the wheel and the sdist, in `dist/` (needs [`uv`](https://docs.astral.sh/uv/)) | +| `just release X.Y.Z` | makes the release tag (see [Releases](#releases)) | + +Changes to `main` go through a pull request. + ## Tests The tests use pytest. In a virtual environment, from a checkout of this repository: @@ -43,7 +57,7 @@ GitHub Actions (`.github/workflows/tests.yml`) runs all tests against the instal A release is an annotated git tag `vX.Y.Z` on `main`. Other projects pin md2misc to a tag (for example as a git submodule), so do not move or delete a tag after it is pushed. -1. Set `version` in `pyproject.toml` to the new version, in the same commit as the last change of the release or in a commit of its own. +1. Set `version` in `pyproject.toml` to the new version, in the pull request of the last change of the release or in a pull request of its own. 2. Make sure that GitHub Actions passes on that commit of `main`. GitHub Actions runs the SCDoc tests too, so SuperCollider is not necessary on your computer. -3. Tag that commit: `git tag -a vX.Y.Z -m "md2misc X.Y.Z"`. The tag and the version in `pyproject.toml` must agree. +3. Check out that commit and tag it: `just release X.Y.Z`. The tag and the version in `pyproject.toml` must agree. 4. Push the tag: `git push origin vX.Y.Z`. A GitHub release for the tag is optional. diff --git a/just/loader.just b/just/loader.just new file mode 100644 index 0000000..546f6ce --- /dev/null +++ b/just/loader.just @@ -0,0 +1,10 @@ +# Managed by Tailor: just/loader.just +import? "tailor.just" +import? "go.just" +import? "python.just" +import? "rust.just" +import? "javascript.just" +import? "shell.just" +import? "go-ffmpeg-statigo.just" +import? "pages.just" +import? "og.just" diff --git a/just/project/build.sh b/just/project/build.sh new file mode 100644 index 0000000..615f83f --- /dev/null +++ b/just/project/build.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# The wheel and the sdist, in dist/. +set -euo pipefail +cd "$(dirname "$0")/../.." +uv build diff --git a/just/project/test.sh b/just/project/test.sh new file mode 100644 index 0000000..90c629d --- /dev/null +++ b/just/project/test.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# All tests, with the Python of .venv if it exists. The SCDoc tests and the +# citation tests are skipped without sclang and pandoc (see docs/development.md). +set -euo pipefail +cd "$(dirname "$0")/../.." +python=.venv/bin/python +[ -x "$python" ] || python=python3 +"$python" -m pytest diff --git a/just/tailor.just b/just/tailor.just new file mode 100644 index 0000000..5667fb6 --- /dev/null +++ b/just/tailor.just @@ -0,0 +1,109 @@ +# Managed by Tailor: just/tailor.just + +# Run explicitly requested setup for enabled components +setup: + @echo "No setup recipes are enabled." + +# Build all enabled ecosystems +build: + #!/usr/bin/env bash + set -euo pipefail + echo "No build recipes are enabled." + project_script='just/project/build.sh' + for parent in just just/project; do + if [[ -L "${parent}" || ( -e "${parent}" && ! -d "${parent}" ) ]]; then + echo "Error: project script parent ${parent} must be a directory, not a symlink" >&2 + exit 1 + fi + done + if [[ -L "${project_script}" || ( -e "${project_script}" && ! -f "${project_script}" ) ]]; then + echo "Error: project script ${project_script} must be a regular file, not a symlink" >&2 + exit 1 + fi + if [[ -f "${project_script}" ]]; then + bash "${project_script}" + fi + +# Run full vet and tests with console coverage +test: + #!/usr/bin/env bash + set -euo pipefail + echo "No test recipes are enabled." + project_script='just/project/test.sh' + for parent in just just/project; do + if [[ -L "${parent}" || ( -e "${parent}" && ! -d "${parent}" ) ]]; then + echo "Error: project script parent ${parent} must be a directory, not a symlink" >&2 + exit 1 + fi + done + if [[ -L "${project_script}" || ( -e "${project_script}" && ! -f "${project_script}" ) ]]; then + echo "Error: project script ${project_script} must be a regular file, not a symlink" >&2 + exit 1 + fi + if [[ -f "${project_script}" ]]; then + bash "${project_script}" + fi + +# Check source without changes, or tidy and format with correct +lint $mode="check": + #!/usr/bin/env bash + set -euo pipefail + case "${mode}" in + check|correct) ;; + *) echo "Error: lint mode must be check or correct" >&2; exit 1 ;; + esac + check_workflows() { + for workflow in .github/workflows/* .github/workflows/.*; do + case "${workflow}" in *.yml|*.yaml) + if [[ -f "${workflow}" ]]; then + actionlint + return + fi ;; + esac + done + echo "No GitHub Actions workflows found. Skipping actionlint." + } + check_workflows + project_script='just/project/lint.sh' + for parent in just just/project; do + if [[ -L "${parent}" || ( -e "${parent}" && ! -d "${parent}" ) ]]; then + echo "Error: project script parent ${parent} must be a directory, not a symlink" >&2 + exit 1 + fi + done + if [[ -L "${project_script}" || ( -e "${project_script}" && ! -f "${project_script}" ) ]]; then + echo "Error: project script ${project_script} must be a regular file, not a symlink" >&2 + exit 1 + fi + if [[ -f "${project_script}" ]]; then + bash "${project_script}" "${mode}" + fi + +# Create a local release tag with just release x.y.z +release $VERSION: + #!/usr/bin/env bash + set -e + + if ! [[ "${VERSION}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Error: VERSION must be in format x.y.z (e.g., 0.1.0)" + exit 1 + fi + + # Require a clean checkout so that the tag matches the local source files. + if [ -n "$(git status --porcelain)" ]; then + echo "Error: Working directory is not clean" + exit 1 + fi + + if git show-ref --tags --verify --quiet "refs/tags/v${VERSION}"; then + echo "Error: Tag v${VERSION} already exists" + exit 1 + fi + + echo "Creating release v${VERSION}..." + git tag -a "v${VERSION}" -m "v${VERSION}" + echo "Tag v${VERSION} created" + echo "" + echo "To publish the release:" + echo " git push origin v${VERSION}" + echo "" diff --git a/justfile b/justfile new file mode 100644 index 0000000..010cfd0 --- /dev/null +++ b/justfile @@ -0,0 +1,9 @@ +# Requires just 1.23.0 or later. +import 'just/loader.just' + +# List available recipes +default: + @just --list + +# Fast check: all tests (they run in seconds) +check: test diff --git a/pyproject.toml b/pyproject.toml index d277073..6a2c729 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [build-system] -requires = ["setuptools>=77"] -build-backend = "setuptools.build_meta" +requires = ["uv_build>=0.13.9,<0.14"] +build-backend = "uv_build" [project] name = "md2misc" @@ -17,8 +17,8 @@ requires-python = ">=3.12" dependencies = [] [project.optional-dependencies] -# the test suite. the SCDoc tests also need sclang (SuperCollider); they are skipped without it -test = ["pytest"] +# the test suite and the checks. the SCDoc tests also need sclang (SuperCollider); they are skipped without it +test = ["pytest", "ruff", "basedpyright"] # `tests/battery.py build`, which makes the TeX fixtures again battery = ["pyyaml", "pathvalidate"] @@ -26,11 +26,12 @@ battery = ["pyyaml", "pathvalidate"] Homepage = "https://github.com/aeskildsen/md2misc" "Derived from" = "https://github.com/paulhectork/md2tex" -[tool.setuptools] -packages = ["md2misc", "md2misc.backends"] - -[tool.setuptools.package-data] -md2misc = ["templates/*.tex"] +[tool.uv.build-backend] +# the package is in the root of the repository, not in src/ +module-root = "" +# The sdist has the complete test setup: the tests, their helper modules and the fixtures. +# tests/fixtures/ATTRIBUTION.md gives the licence of the fixtures. +source-include = ["tests/**"] [tool.pytest.ini_options] testpaths = ["tests"] From a1153fd84895b28e30cb3f8c81a7753d9868833c Mon Sep 17 00:00:00 2001 From: Anders Eskildsen <22001464+aeskildsen@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:59:24 +0100 Subject: [PATCH 2/5] style: format with ruff at line length 120 Format the Python code with `ruff format`, line length 120, and add `ruff.toml`. There are no hand-made changes. Checked: the syntax tree of each file is the same as before, except the trailing white space in one docstring. All tests pass with `sclang`, and the test fixtures have no change. Stacked on #2. --- md2misc/__init__.py | 12 +- md2misc/backends/minted.py | 5 +- md2misc/backends/schelp.py | 212 +++++++++++++++++++--------- md2misc/backends/tex.py | 22 ++- md2misc/citations.py | 12 +- md2misc/converters.py | 117 +++++++++------- md2misc/core.py | 34 +++-- md2misc/errors_warnings.py | 13 +- md2misc/helpers.py | 22 +-- md2misc/tables.py | 9 +- ruff.toml | 16 +++ tests/battery.py | 23 +-- tests/schelp_cases.py | 247 +++++++++++++++++++-------------- tests/schelp_fixtures.py | 13 +- tests/test_schelp_behavior.py | 85 +++++++----- tests/test_schelp_citations.py | 50 ++++--- tests/test_schelp_errors.py | 12 +- tests/test_schelp_golden.py | 1 + tests/test_schelp_methods.py | 224 ++++++++++++++++++++---------- tests/test_schelp_render.py | 1 + tests/test_schelp_tables.py | 55 +++++--- tests/test_schelp_writer.py | 1 + tests/test_tables.py | 182 ++++++++++++++++-------- tests/test_tex_battery.py | 1 + tests/test_tex_library.py | 6 +- 25 files changed, 888 insertions(+), 487 deletions(-) create mode 100644 ruff.toml diff --git a/md2misc/__init__.py b/md2misc/__init__.py index 3df0d53..fb9f692 100644 --- a/md2misc/__init__.py +++ b/md2misc/__init__.py @@ -1,5 +1,13 @@ from .core import convert, convert_schelp, default_template from .errors_warnings import DocumentError, Md2miscError, Md2miscWarning, ParsingException, UnsupportedConstruct -__all__ = ["convert", "convert_schelp", "default_template", - "Md2miscError", "Md2miscWarning", "DocumentError", "ParsingException", "UnsupportedConstruct"] +__all__ = [ + "convert", + "convert_schelp", + "default_template", + "Md2miscError", + "Md2miscWarning", + "DocumentError", + "ParsingException", + "UnsupportedConstruct", +] diff --git a/md2misc/backends/minted.py b/md2misc/backends/minted.py index 854a49e..b68974e 100644 --- a/md2misc/backends/minted.py +++ b/md2misc/backends/minted.py @@ -1,4 +1,3 @@ - # -------------------------------------------------------------------------- # list of languages supported by pygments/minted (01.11.2024) # source: https://pygments.org/languages/ @@ -909,5 +908,5 @@ "bro", "zephir", "zig", - "zone" -] \ No newline at end of file + "zone", +] diff --git a/md2misc/backends/schelp.py b/md2misc/backends/schelp.py index a7cdb0c..1eda861 100644 --- a/md2misc/backends/schelp.py +++ b/md2misc/backends/schelp.py @@ -46,8 +46,12 @@ 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", - "instance methods": "INSTANCEMETHODS"} + special_sections = { + "description": "DESCRIPTION", + "examples": "EXAMPLES", + "class methods": "CLASSMETHODS", + "instance methods": "INSTANCEMETHODS", + } # 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 @@ -93,7 +97,9 @@ def _header_value(cls, key: str, value, line: int = None): else a string. """ if key not in cls.header_keys: - raise UnsupportedConstruct(cls.name, f"front matter key `{key}` (the keys are {', '.join(cls.header_keys)})", line) + raise UnsupportedConstruct( + cls.name, f"front matter key `{key}` (the keys are {', '.join(cls.header_keys)})", line + ) if key in cls.list_keys: if isinstance(value, str): value = value.split(",") @@ -150,7 +156,7 @@ def take_front_matter(self, markdown: str) -> tuple: if isinstance(value, str): value = self._unquote(value) values[key] = self._header_value(key, value, line_number) - return values, "\n" * (end + 1) + "\n".join(lines[end + 1:]) + return values, "\n" * (end + 1) + "\n".join(lines[end + 1 :]) def header(self, values: dict) -> str: """ @@ -165,8 +171,10 @@ def header(self, values: dict) -> str: if not values: return "" if "title" not in values and "class" not in values: - raise DocumentError("the header of a schelp document needs a title or a class: " - "use `title:` or `class:` in the front matter, a level 1 heading, or give the value") + raise DocumentError( + "the header of a schelp document needs a title or a class: " + "use `title:` or `class:` in the front matter, a level 1 heading, or give the value" + ) out = "" for key in self.header_keys: if key in values: @@ -189,8 +197,13 @@ def check_insertions(self): """ unused = sorted(set(self.insertions) - self.used_insertions) if unused: - raise DocumentError("the document has no insertion point for: " + ", ".join(unused) - + " (a line like ``)") + raise DocumentError( + "the document has no insertion point for: " + + ", ".join(unused) + + " (a line like ``)" + ) # ------------------------------------------------------------ checks @@ -200,8 +213,9 @@ def check_insertions(self): # 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)") + 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]*$" @@ -214,17 +228,20 @@ def _is_paragraph_line(self, line: str) -> bool: whether the line can be a line of a paragraph: it is not empty and it does not start another construct. """ return bool(line.strip()) and not ( - re.match(self.list_item_regex, line) or re.match(syntax.HEADING_STRICT, line) + re.match(self.list_item_regex, line) + or re.match(syntax.HEADING_STRICT, line) or line.lstrip().startswith((">", syntax.CODE_FENCE, "|")) ) def _check_heading_source(self, text: str, line: int): # the name of a section is plain text - if (self.code_token[0] in text or re.search(r"\*[^*\n]+\*", text) - or re.search(syntax.INLINE_MATH_STRICT, text)): + 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) - or re.search(syntax.CITATION, text)): + 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): @@ -233,12 +250,12 @@ def _check_citation(self, citation: str, line: int = None): 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) + 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) + 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: """ @@ -261,8 +278,9 @@ def _check_table(self, lines: list, number: int, in_methods: bool, in_method: bo self.unsupported("`|` in code in a table (write `\\|`)", index + 1) header = tables.split_row(lines[number]) 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) + self.unsupported( + "table whose delimiter row has another number of cells than its header row", header_line + 1 + ) if end == number + 2: self.unsupported("table without rows", header_line) for index in range(number + 2, end): @@ -276,11 +294,19 @@ def _check_table(self, lines: list, number: int, in_methods: bool, in_method: bo 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) + 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): @@ -291,8 +317,9 @@ def _check_argument_table(self, lines: list, number: int, end: int): 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) + 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() @@ -329,9 +356,14 @@ def image_problem(cls, caption: str, path: str): 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)): + 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 @@ -347,9 +379,14 @@ def _check_quote_line(self, text: str, line: int): 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)): + 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" @@ -372,7 +409,8 @@ def footnote_paragraphs(self, lines: list, number: int) -> list: 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)): + self._is_paragraph_line(line) or re.match(self.indented_regex, line) + ): break paragraphs[-1].append(index) index += 1 @@ -392,8 +430,11 @@ def join_footnotes(self, string: str) -> str: 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)) + 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) @@ -407,18 +448,28 @@ def _check_method_part(self, lines: list, number: int, in_methods: bool, part): checked in `check_source()`. """ line = 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)): + 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 or a " - "`#### Discussion` heading 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 (put a `#### Discussion` heading " - "before it)", 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): @@ -479,20 +530,29 @@ def check_source(self, markdown: str): if level == 1: level_1_headings += 1 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) + 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: methods_mark = self.methods_sections.get(heading[3].strip().lower()) method_part = None if methods_mark and level == 3 and re.match(self.method_heading_regex(methods_mark), line): method_part = "text" - elif (methods_mark and method_part not in (None, "discussion") - and re.match(self.discussion_heading_regex, line)): + 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) + 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): @@ -517,8 +577,9 @@ def check_source(self, markdown: str): if re.search(syntax.AUDIO, text): self.unsupported("audio file", 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) + 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): @@ -537,8 +598,11 @@ def check_source(self, markdown: str): for emphasis in chain(re.finditer(syntax.BOLD, text), re.finditer(syntax.ITALIC, text)): if self.code_token[0] in emphasis[1]: self.unsupported("code inside bold or italic text", line_number) - if (re.search(syntax.LINK, emphasis[1]) or re.search(self.footnote_mark_regex, emphasis[1]) - or re.search(syntax.CITATION, emphasis[1])): + if ( + re.search(syntax.LINK, emphasis[1]) + or re.search(self.footnote_mark_regex, emphasis[1]) + or re.search(syntax.CITATION, emphasis[1]) + ): self.unsupported("link, footnote or citation inside bold or italic text", line_number) if re.match(self.footnote_definition_regex, text): # the lines after the definition line @@ -550,8 +614,10 @@ def check_source(self, markdown: str): is_quote = text.startswith(">") if is_quote and not previous_is_quote: if re.match(self.alert_mark_regex, text) and not self.admonition_tag(text): - self.unsupported("alert of a kind that is not known (the kinds are " - + ", ".join(self.admonitions) + ")", line_number) + self.unsupported( + "alert of a kind that is not known (the kinds are " + ", ".join(self.admonitions) + ")", + line_number, + ) plain_quote = not self.admonition_tag(text) if is_quote and plain_quote: self._check_quote_line(text, line_number) @@ -592,7 +658,9 @@ def heading(self, level: int, text: str) -> str: if level == 1: # the title of the document: it goes in the header, which escapes it if self.title_heading is not None: - self.unsupported("second level 1 heading (the first one is the title of the document: use level 2 for sections)") + self.unsupported( + "second level 1 heading (the first one is the title of the document: use level 2 for sections)" + ) self.title_heading = self._unescape(text.strip()) return "" special = self.special_sections.get(text.strip().lower()) if level == 2 else None @@ -675,9 +743,14 @@ def _quote(self, lines: list) -> str: mark = re.escape(self.code_token[0]) if any("\n" in self.stash[token] for token in re.findall(mark + r"\d+" + mark, paragraph)): self.unsupported("code block in a block quote") - if (self.code_token[0] in paragraph or "*" in paragraph - or re.search(syntax.MATH_TOKEN_REGEX, paragraph) or re.search(self.tag_regex, paragraph) - or re.search(syntax.LINK, paragraph) or re.search(self.footnote_mark_regex, paragraph)): + if ( + self.code_token[0] in paragraph + or "*" in paragraph + or re.search(syntax.MATH_TOKEN_REGEX, paragraph) + or re.search(self.tag_regex, paragraph) + or re.search(syntax.LINK, paragraph) + or re.search(self.footnote_mark_regex, paragraph) + ): self.unsupported(self.markup_in_quote_construct) if not paragraphs: return "" @@ -831,7 +904,7 @@ def write_citations(self, string: str) -> str: out, position = [], 0 for index, citation in enumerate(found): - before = string[position:citation.start()] + before = string[position : citation.start()] if index in in_footnote: text = parts[index][0] else: @@ -875,7 +948,7 @@ def _entries(self, entries: dict) -> dict: text = self._pandoc_text(inlines) authors = re.match(r"(.+?)\.\s(?=\d{4}|n\.d\.)", previous) if text.startswith("β€”β€”β€”") and authors: - text = authors[1] + text[len("β€”β€”β€”"):].lstrip("β€”") + text = authors[1] + text[len("β€”β€”β€”") :].lstrip("β€”") out[key] = previous = text return out @@ -968,9 +1041,18 @@ def clean(self, string: str) -> str: # already (see `write_citations()`) string = re.sub(self.after_letter + r"footnote::", " footnote::", string) # the other inline tags get a word joiner. code and math are still tokens here - string = re.sub(self.after_letter + r"(?=(strong|emphasis|link)::|" + syntax.MATH_TOKEN_REGEX + "|" - + re.escape(self.code_token[0]) + r"\d+" + re.escape(self.code_token[0]) + ")", - self.word_joiner, string) + string = re.sub( + self.after_letter + + r"(?=(strong|emphasis|link)::|" + + syntax.MATH_TOKEN_REGEX + + "|" + + re.escape(self.code_token[0]) + + r"\d+" + + re.escape(self.code_token[0]) + + ")", + self.word_joiner, + string, + ) # paragraphs are separated by one empty line; the document ends with one line ending string = re.sub(r"\n{3,}", "\n\n", string).strip("\n") return string + "\n" if string else "" diff --git a/md2misc/backends/tex.py b/md2misc/backends/tex.py index 26489b7..465c6de 100644 --- a/md2misc/backends/tex.py +++ b/md2misc/backends/tex.py @@ -24,8 +24,14 @@ class TeXBackend(Backend): "article": ["section", "subsection", "subsubsection"], "book": ["chapter", "section", "subsection", "subsubsection"], } - def __init__(self, unnumbered: bool = False, document_class: str = "article", - minted_language: str = "text", override_language: bool = False): + + def __init__( + self, + unnumbered: bool = False, + document_class: str = "article", + minted_language: str = "text", + override_language: bool = False, + ): self.unnumbered = unnumbered self.document_class = document_class self.minted_language = minted_language @@ -47,7 +53,7 @@ def escape(self, string: str) -> str: string = string.replace("$", r"\$") string = string.replace("%", r"\%") string = string.replace(r"$", r"\&") - #string = string.replace(r"~", r"\~") # leads to an error if ~ is used in an inline quote + # string = string.replace(r"~", r"\~") # leads to an error if ~ is used in an inline quote string = string.replace("_", r"\_") string = string.replace("&", r"\&") string = re.sub(r"\^", r"\\^", string, flags=re.M) @@ -199,7 +205,7 @@ def code_block(self, code: str, language: str = None, title: str = None, highlig # titles are converted to captions if title: - env = env.replace("@@CAPTIONTOKEN@@", r'\caption{' + title + r'}') + env = env.replace("@@CAPTIONTOKEN@@", r"\caption{" + title + r"}") else: # remove captiontoken line env = env.replace("@@CAPTIONTOKEN@@\n", "") @@ -246,6 +252,10 @@ def clean(self, string: str) -> str: # string = re.sub(r"{\s+", r"{", string, flags=re.M) # remove whitespace after opening curly brace # string = re.sub(r"\s+}", r"}", string, flags=re.M) # remove whitespace before closing curly brace string = re.sub(r"\n{2,}", r"\n\n", string, flags=re.M) # reduce 2+ consecutive newlines to 2 - string = re.sub(r"(\\begin\{.*?)\n{2,}", r"\1\n", string, flags=re.M) # replace multiple consecutive newlines after \begin with just one - string = re.sub(r"\n{2,}( *\\end\{)", r"\n\1", string, flags=re.M) # replace multiple consecutive newlines before \end with just one + string = re.sub( + r"(\\begin\{.*?)\n{2,}", r"\1\n", string, flags=re.M + ) # replace multiple consecutive newlines after \begin with just one + string = re.sub( + r"\n{2,}( *\\end\{)", r"\n\1", string, flags=re.M + ) # replace multiple consecutive newlines before \end with just one return string diff --git a/md2misc/citations.py b/md2misc/citations.py index 0d824cd..39fdb5b 100644 --- a/md2misc/citations.py +++ b/md2misc/citations.py @@ -6,6 +6,7 @@ the output of Pandoc is its JSON form (the document tree), so that the text of a citation does not need to be read as Markdown again. """ + import json import os import shutil @@ -25,8 +26,10 @@ def find_pandoc() -> str: """ path = os.environ.get("PANDOC") or shutil.which("pandoc") if not path: - raise DocumentError("citations need the program `pandoc`: put it on the PATH, or set the environment " - "variable PANDOC to its path") + raise DocumentError( + "citations need the program `pandoc`: put it on the PATH, or set the environment " + "variable PANDOC to its path" + ) return path @@ -45,8 +48,9 @@ def process(citations: list, bibliography) -> tuple: source = "".join(citation + "\n\n" for citation in citations) + "::: {#refs}\n:::\n" pandoc = find_pandoc() try: - done = subprocess.run([pandoc, *PANDOC_ARGUMENTS, "--bibliography", str(path)], - input=source, capture_output=True, text=True) + done = subprocess.run( + [pandoc, *PANDOC_ARGUMENTS, "--bibliography", str(path)], input=source, capture_output=True, text=True + ) except OSError as error: raise DocumentError(f"md2misc could not run pandoc (`{pandoc}`): {error}") from error if done.returncode != 0: diff --git a/md2misc/converters.py b/md2misc/converters.py index 3cd0df9..13aaaee 100644 --- a/md2misc/converters.py +++ b/md2misc/converters.py @@ -18,6 +18,7 @@ class MDSimple: simple substitutions: bold, italics, audio files, horizontal rules, line breaks. the output is written by the backend. """ + bold_regex = syntax.BOLD italic_regex = syntax.ITALIC audio_regex = syntax.AUDIO @@ -50,6 +51,7 @@ class MDHeader: - mark(): replace the `#` characters of each header by a marker that holds the header level - convert(): replace the marked headers by the output of the backend """ + marker = "\x00{}\x00" marker_regex = r"\x00(\d+)\x00" @@ -63,11 +65,7 @@ def mark(string: str, backend: Backend): :return: the text with marked headers """ # a `>` is replaced by a space by the block quote step, thus a header can follow it - return re.sub( - backend.heading_regex, - lambda m: m[1] + MDHeader.marker.format(len(m[2])), - string, flags=re.M - ) + return re.sub(backend.heading_regex, lambda m: m[1] + MDHeader.marker.format(len(m[2])), string, flags=re.M) @staticmethod def convert(string: str, backend: Backend): @@ -82,15 +80,14 @@ def convert(string: str, backend: Backend): # one pass per header level, from the first level up. the last pass takes all # remaining levels. a later pass removes the blank lines that an earlier pass left for group in range(1, backend.heading_groups + 1): + def write_heading(m): level = int(m[1]) if level == group or (group == backend.heading_groups and level > group): return backend.heading(level, m[2]) return m[0] # a header of another pass - string = re.sub( - r"^\s*" + MDHeader.marker_regex + r" *(.*?)$", - write_heading, string, flags=re.M - ) + + string = re.sub(r"^\s*" + MDHeader.marker_regex + r" *(.*?)$", write_heading, string, flags=re.M) string = re.sub(MDHeader.marker_regex, lambda m: backend.escape("#" * int(m[1])), string) return string @@ -104,6 +101,7 @@ class MDQuote: block_quote(): replace multiline markdown quotes (">") into quotes of the output format inline_quote(): transform markdown quotes (`"`, `'`) into quotes of the output format """ + @staticmethod def block_quote(string: str, backend: Backend): r""" @@ -114,11 +112,7 @@ def block_quote(string: str, backend: Backend): :param backend: the output format :return: the updated string representation of a markdown file """ - string = re.sub( - backend.block_quote_regex, - lambda m: backend.block_quote(m[1]), - string, flags=re.M - ) + string = re.sub(backend.block_quote_regex, lambda m: backend.block_quote(m[1]), string, flags=re.M) return backend.remove_quote_marks(string) @staticmethod @@ -149,6 +143,7 @@ class MDList: ordered_l(): create ordered lists from md numbered lists definition_l(): create definition lists from md definition lists """ + @staticmethod def unordered_l(string: str, backend: Backend): """ @@ -195,7 +190,7 @@ def ordered_l(string: str, backend: Backend): string = string.replace("@@LISTTOKEN@@", backend.ordered_list(lsitems)) return string - + @staticmethod def definition_l(string: str, backend: Backend): """ @@ -224,9 +219,9 @@ def definition_l(string: str, backend: Backend): if current_list: lists.append(current_list) - + for ls in lists: - ls_block = ''.join([l[0] for l in ls]) + ls_block = "".join([l[0] for l in ls]) entries = [] # list of (term, definition) for item in ls: @@ -250,6 +245,7 @@ class MDCode: block_code(): create a code block of the output format from a md block of code inline_code(): create inline code of the output format from inline md code """ + @staticmethod def inline_code(string: str, backend: Backend): """ @@ -259,19 +255,19 @@ def inline_code(string: str, backend: Backend): :param backend: the output format :return: the updated string representation """ - + matches = re.finditer(syntax.INLINE_CODE, string) for m in matches: code = m[0] string = string.replace(code, backend.inline_code(m[1])) - + return string @staticmethod def block_code(string: str, backend: Backend): """ translate a markdown block of code into a code block of the output format. - + the function tries to match a md block code "```...```". if the block of code is matched, the code body is given to the backend. @@ -298,14 +294,14 @@ def block_code(string: str, backend: Backend): if backend.strip_quote_marks_in_code: # a code block in a block quote: each line of the code starts with the quote marks of the fence line - prefix = source[source.rfind("\n", 0, m.start()) + 1:m.start()] + prefix = source[source.rfind("\n", 0, m.start()) + 1 : m.start()] if re.fullmatch(r"[ \t]*(>[ \t]*)+", prefix): depth = prefix.count(">") code_body = re.sub(r"^[ \t]*(?:>[ \t]?){1,%d}" % depth, "", code_body, flags=re.M) # assume language is the first word in the info string # cf. https://spec.commonmark.org/0.31.2/#fenced-code-blocks - lang_info = re.search(r'^([0-9A-Za-z_-]+) *', info_string) + lang_info = re.search(r"^([0-9A-Za-z_-]+) *", info_string) language = lang_info[1] if lang_info else None # titles specified like title="A nice code block" in the info string @@ -325,13 +321,14 @@ def block_code(string: str, backend: Backend): class MDReference: r""" substitutions for references inside a markdown document. - + contains -------- footnote(): replace markdown footnotes (`[\^\d+]`) into footnotes of the output format hyperlink(): replace markdown hyperlinks into hyperlinks of the output format citation(): replace pandoc-style references `[@doe1979]` into citations of the output format """ + @staticmethod def footnote(string: str, backend: Backend): r""" @@ -360,8 +357,7 @@ def footnote(string: str, backend: Backend): pointer = match[0] # extract the footnote pointer (the pointer to the actual footnote) fnote_num = re.search(r"\d+", pointer)[0] # extract the footnote nΒ° fnote_text = re.search( - r"^(\[" + caret + fnote_num + r"\]:) *(.+\n?)", - string, flags=re.M + r"^(\[" + caret + fnote_num + r"\]:) *(.+\n?)", string, flags=re.M ) # match the proper footnote (with the good fnote_num) # remove the pointer + normalize space note = re.sub(r"\s+", " ", fnote_text[0].replace(fnote_text[1], "")).strip() @@ -385,7 +381,7 @@ def footnote(string: str, backend: Backend): string = re.sub(r"(\[" + caret + r"\d+\]:)(.+\n?)*", "", string, flags=re.M) return string - + @staticmethod def hyperlink(string: str, backend: Backend): r""" @@ -400,7 +396,7 @@ def hyperlink(string: str, backend: Backend): if link[2].startswith("http"): # External URL string = string.replace(link[0], backend.link(link[2], link[1])) - else: # We are dealing with some other link, likely to another internal document + else: # We are dealing with some other link, likely to another internal document written = backend.internal_link(link[2], link[1]) if written is not None: string = string.replace(link[0], written) @@ -412,7 +408,7 @@ def hyperlink(string: str, backend: Backend): Warnings("link_type_not_supported", link[2]) return string - + @staticmethod def citation(string: str, backend: Backend): r""" @@ -422,12 +418,12 @@ def citation(string: str, backend: Backend): pandoc citation syntax spec: https://pandoc.org/chunkedhtml-demo/8.20-citation-syntax.html biblatex docs: https://ctan.org/pkg/biblatex - + Input syntax: - Citation form: [citationkey, locator] - Citation key: `@doe1999` (`-@doe1999` will omit author name with the \parencite* command) - Locator syntax: `p. 30`, `30`, `pp. 30-35`, `30-35` are the only valid forms - + Conversion examples: - [@doe1999] -> \parencite{doe1999} - [-@doe1999] -> \parencite*{doe1999} @@ -436,7 +432,7 @@ def citation(string: str, backend: Backend): - [@doe1999, 30-35] -> \parencite[pp. 30-35]{doe1999} - [@doe1999, pp. 30-35] -> \parencite[pp. 30-35]{doe1999} - [@doe1999; @smith] -> \parencites{doe1999, smith} - + Limitations: - Prefix or suffix not supported currently - Multiple sources in same citation are only supported in the basic form `[@doe1999; @smith2000]`, i.e. without locator or pre-/suffix @@ -454,24 +450,24 @@ def citation(string: str, backend: Backend): # Use negative lookahead so we don't match links or images ref_strings = re.finditer(syntax.CITATION, string, re.M) for ref_string in ref_strings: - if ';' in ref_string[1]: + if ";" in ref_string[1]: # multiple references in one citation # -> simple mode - keys = ref_string[1].replace(';', ',').replace('@', '') + keys = ref_string[1].replace(";", ",").replace("@", "") citation_text = backend.citations(keys) else: # only one citation, so we split into citation key and locator ref_components = re.match(r"(-?@[^, ]+)(, (?:p\. )?(\d+\b(?!-))|, (?:pp\. )?(\d+-\d+))?", ref_string[1]) citation_key = ref_components[1] locator = ref_components[3] or ref_components[4] - omit_author = citation_key.startswith('-') + omit_author = citation_key.startswith("-") citation_text = backend.citation( citation_key[2:] if omit_author else citation_key[1:], locator, is_range=not ref_components[3], - omit_author=omit_author + omit_author=omit_author, ) - + string = string.replace(ref_string[0], citation_text) return string @@ -487,6 +483,7 @@ class MDCleaner: from the rest of the pipeline clean_output(): clean the text created and reinsert code substrings at the end of the pipeline """ + @staticmethod def prepare_markdown(string: str, backend: Backend): """ @@ -513,8 +510,8 @@ def prepare_markdown(string: str, backend: Backend): # the code is replaced in `string` with a special token string, codedict = backend.stash_code(string) - string = string.replace("{==", "") # begin highlight (removed) - string = string.replace("==}", "") # end highlight (removed) + string = string.replace("{==", "") # begin highlight (removed) + string = string.replace("==}", "") # end highlight (removed) return string, codedict @@ -547,7 +544,7 @@ class MDFrontmatter: """ remove Markdown file frontmatter written in YAML format """ - + @staticmethod def convert(string: str): """ @@ -555,7 +552,7 @@ def convert(string: str): :param string: the string rpr of the markdown file to convert :return: string with the conversion performed """ - + flags = re.MULTILINE | re.DOTALL string = re.sub(r"^---.*---", "", string, flags=flags) @@ -566,7 +563,7 @@ class MDMedia: """ Convert embedded media (currently only images) """ - + @staticmethod def image(string: str, backend: Backend): r""" @@ -582,7 +579,7 @@ def image(string: str, backend: Backend): :param backend: the output format :return: string with the conversion performed """ - default_width = "85" # percent + default_width = "85" # percent # this regex looks a little weird, but we need to match the escaped chars introduced earlier... open_brace = re.escape(backend.escape("{")) @@ -590,12 +587,13 @@ def image(string: str, backend: Backend): percent = re.escape(backend.escape("%")) images = re.finditer( syntax.IMAGE + r"(?:" + open_brace + r".*?width=\"(\d+)" + percent + r"\".*?" + close_brace + r")?", - string, re.M + string, + re.M, ) for match in images: width = match[3] if match[3] else default_width string = string.replace(match[0], backend.image(match[1], match[2], width)) - + return string @@ -655,6 +653,7 @@ class MDInsertion: insertion points: a line with an HTML comment, like ``, marks a place where the caller of the conversion can put text. the comment is not shown by Markdown viewers. """ + placeholder = syntax.INSERTION @staticmethod @@ -681,6 +680,7 @@ class MDMethods: `convert()` writes the tags after the other steps. the marker lines start with a control character, so that no other step takes a cell text for a list, a quote or a heading. """ + marker = "\x02" separator = "\x03" # between the text of an argument and the values of the other columns level_2_regex = r"^##(?!#)[ \t]+(.*?)[ \t]*$" @@ -692,13 +692,20 @@ def _arguments(lines: list, number: int, end: int) -> list: """ header = [tables.unescape(cell) for cell in tables.split_row(lines[number])] out = [] - for row in lines[number + 2:end]: + for row in lines[number + 2 : end]: cells = [tables.unescape(cell) for cell in tables.split_row(row)] cells += [""] * (len(header) - len(cells)) name = cells[0].strip("`") others = [f"{header[i]}: {cells[i]}" for i in range(1, len(header) - 1) if cells[i]] - out.append(MDMethods.marker + "ARGUMENT" + MDMethods.marker + name + MDMethods.marker + cells[-1] - + "".join(MDMethods.separator + other for other in others)) + out.append( + MDMethods.marker + + "ARGUMENT" + + MDMethods.marker + + name + + MDMethods.marker + + cells[-1] + + "".join(MDMethods.separator + other for other in others) + ) return out @staticmethod @@ -740,10 +747,13 @@ def mark(string: str, backend: Backend): out += [""] + "\n\n".join(MDMethods._arguments(lines, number, end)).split("\n") + [""] number = end continue - elif (in_method and not in_discussion and line.startswith(backend.returns_mark) - and (number == 0 or not lines[number - 1].strip())): - line = (MDMethods.marker + "RETURNS" + MDMethods.marker - + line[len(backend.returns_mark):].strip()) + elif ( + in_method + and not in_discussion + and line.startswith(backend.returns_mark) + and (number == 0 or not lines[number - 1].strip()) + ): + line = MDMethods.marker + "RETURNS" + MDMethods.marker + line[len(backend.returns_mark) :].strip() out.append(line) number += 1 return "\n".join(out) @@ -771,6 +781,7 @@ class MDTable: `convert()` gives the rows to the backend after the other steps. a marker line starts with a control character, so that no other step takes a cell text for a list, a quote or a heading. """ + marker = "\x04" separator = "\x05" # between the cells of a row start = marker + "TABLE" @@ -819,9 +830,9 @@ def write(match): header, rows = None, [] for line in match[1].split("\n"): if line.startswith(MDTable.header): - header = line[len(MDTable.header):].split(MDTable.separator) + header = line[len(MDTable.header) :].split(MDTable.separator) elif line.startswith(MDTable.row): - rows.append(line[len(MDTable.row):].split(MDTable.separator)) + rows.append(line[len(MDTable.row) :].split(MDTable.separator)) return backend.table(header, rows) return re.sub(re.escape(MDTable.start) + r"\n(.*?)\n" + re.escape(MDTable.end), write, string, flags=re.S) diff --git a/md2misc/core.py b/md2misc/core.py index 6fa202b..35c0b9f 100644 --- a/md2misc/core.py +++ b/md2misc/core.py @@ -2,7 +2,21 @@ from .backends import SchelpBackend, TeXBackend from .errors_warnings import DocumentError -from .converters import MDSimple, MDQuote, MDList, MDCode, MDCleaner, MDReference, MDHeader, MDFrontmatter, MDInsertion, MDMedia, MDMath, MDMethods, MDTable +from .converters import ( + MDSimple, + MDQuote, + MDList, + MDCode, + MDCleaner, + MDReference, + MDHeader, + MDFrontmatter, + MDInsertion, + MDMedia, + MDMath, + MDMethods, + MDTable, +) def default_template() -> str: @@ -28,8 +42,10 @@ def convert(data, unnumbered=False, document_class="article", minted_language="t """ if document_class not in TeXBackend.sectioning: - raise DocumentError(f"the document class `{document_class}` is not supported: " - + "the document classes are `article` and `book`") + raise DocumentError( + f"the document class `{document_class}` is not supported: " + + "the document classes are `article` and `book`" + ) backend = TeXBackend(unnumbered, document_class, minted_language, override_language) return run_pipeline(data, backend) @@ -74,19 +90,19 @@ def run_pipeline(data, backend): backend.check_source(data) # complex replacements - data = MDCode.block_code(data, backend) # the contents of code blocks and inline code strings + data = MDCode.block_code(data, backend) # the contents of code blocks and inline code strings # must be interpreted verbatim. therefore, # these functions come first so that they won't be changed # by `prepare_markdown()` - data = MDMethods.mark(data, backend) # argument tables: after code blocks, and before inline code, + 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 = 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 = MDInsertion.apply(data, backend) # text of the caller is not changed, either data, mathdict = MDMath.stash_math(data, backend) data, codedict = MDCleaner.prepare_markdown(data, backend) # remove code from the pipeline - data = MDHeader.mark(data, backend) # headers are located before the text is escaped - data = backend.escape(data) # escape special chars + data = MDHeader.mark(data, backend) # headers are located before the text is escaped + data = backend.escape(data) # escape special chars data = MDFrontmatter.convert(data) data = MDMedia.image(data, backend) data = MDQuote.inline_quote(data, backend) diff --git a/md2misc/errors_warnings.py b/md2misc/errors_warnings.py index 4d0dafb..fbc8eee 100644 --- a/md2misc/errors_warnings.py +++ b/md2misc/errors_warnings.py @@ -11,6 +11,7 @@ class Md2miscError(Exception): """ base class for all errors of md2misc. `message` holds the text of the error. """ + def __init__(self, message: str): super().__init__(message) self.message = message @@ -31,6 +32,7 @@ class UnsupportedConstruct(Md2miscError): a Markdown construct that the output format cannot write. `line` is the line of the construct, if known. `describe(source)` gives the message with the name of the Markdown file. """ + def __init__(self, backend: str, construct: str, line: int = None): """ :param backend: the name of the output format @@ -72,14 +74,14 @@ class IndentationException(ParsingException): """ error logs relative to list indentation """ + logs = { "firstindent": "ERROR. - inconsistant indentation in markdown list \n" - + "`@@TOKEN@@` \n" - + "all items must be as indented than the first list item or more.", + + "`@@TOKEN@@` \n" + + "all items must be as indented than the first list item or more.", "multiplier": "ERROR. inconsistant indentation level in list \n" - + "`@@TOKEN@@` \nall list items must share a common indentation multiplier.\n" - + "the first indented item defines the indentation multiplier." - + + "`@@TOKEN@@` \nall list items must share a common indentation multiplier.\n" + + "the first indented item defines the indentation multiplier.", } # all possible error logs def __init__(self, key, lstext): @@ -94,6 +96,7 @@ class Warnings: """ class to give custom warnings, with the category `Md2miscWarning`. the warnings do not change the output. """ + logs = { "list_deep_nesting": "deep list nesting. you may need to change base tex options in the header.", "lang_not_supported": "language `@@TOKEN@@` is not supported by minted/Pygments. see https://pygments.org/languages/ for a list of supported languages.", diff --git a/md2misc/helpers.py b/md2misc/helpers.py index 1a02dc9..a9368aa 100644 --- a/md2misc/helpers.py +++ b/md2misc/helpers.py @@ -48,10 +48,12 @@ def process_list_indentation(lstext): if indent < 0: raise IndentationException(key="firstindent", lstext=lstext) # raise an error, print error msg, exit else: - lsitems.append([ - re.sub(r"^\s*-\s*", "", item), # item content - indent # indentation (nΒ° of spaces) - ]) + lsitems.append( + [ + re.sub(r"^\s*-\s*", "", item), # item content + indent, # indentation (nΒ° of spaces) + ] + ) # if there are different indentation levels, # - check that all levels have a common multiplier @@ -79,11 +81,11 @@ def process_list_indentation(lstext): def get_matching_brackets(code: str): r""" - Finds and returns the substring of the input code contained by an + Finds and returns the substring of the input code contained by an outer pair of matching opening and closing curly brackets `{...}`, assuming that any inner pairs of brackets which are opened are closed again. - + Escaped brackets `\{` and `\}` are ignored. - + :param code: The input string containing code with curly brackets. :return: The substring from the start of the input code up to and including the matching closing bracket. @@ -92,14 +94,14 @@ def get_matching_brackets(code: str): numOpened = 0 hasOpened = False for c in code: - if c == '{' and code[pos-1] != "\\": + if c == "{" and code[pos - 1] != "\\": numOpened += 1 hasOpened = True - elif c == '}' and code[pos-1] != "\\": + elif c == "}" and code[pos - 1] != "\\": numOpened -= 1 if numOpened == 0 and hasOpened: # we found the closing bracket pos += 1 break pos += 1 - return code[:pos] \ No newline at end of file + return code[:pos] diff --git a/md2misc/tables.py b/md2misc/tables.py index a57006b..646ce5c 100644 --- a/md2misc/tables.py +++ b/md2misc/tables.py @@ -8,6 +8,7 @@ the backends use these functions to find tables in the source and in the converters, so that both find the same tables. """ + import re # a cell of the delimiter row. the colons give the alignment, which no backend uses @@ -74,8 +75,12 @@ def starts_table(lines: list, number: int) -> bool: if number + 1 >= len(lines): return False header = lines[number] - return (bool(header.strip()) and has_pipe(header) and indent(header) <= MAX_INDENT - and is_delimiter_row(lines[number + 1])) + return ( + bool(header.strip()) + and has_pipe(header) + and indent(header) <= MAX_INDENT + and is_delimiter_row(lines[number + 1]) + ) # a line that starts another block ends a table. other lines without a pipe would be rows in GFM, but not in diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..5470aa8 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,16 @@ +line-length = 120 +include = ["*.py", "*.pyi"] +force-exclude = true +preview = false +unsafe-fixes = false + +[lint] +select = [ + "E4", "E7", "E9", "F", "I", "UP", "C4", + "B006", "B007", "B012", "B018", "B023", "B024", "B027", + "RUF100", +] + +[lint.pyupgrade] +# Runtime annotation consumers still need syntax that the Python floor supports. +keep-runtime-typing = true diff --git a/tests/battery.py b/tests/battery.py index 2397a14..cde1612 100644 --- a/tests/battery.py +++ b/tests/battery.py @@ -20,6 +20,7 @@ python3 tests/battery.py build """ + import argparse import contextlib import importlib @@ -121,6 +122,7 @@ def count_constructs(md: str) -> dict: # ------------------------------------------------------------------ build + def export_book(): """Export the docs folder of the book at the fixed commit.""" if BOOK_EXPORT.exists(): @@ -128,7 +130,8 @@ def export_book(): BOOK_EXPORT.mkdir() archive = subprocess.run( ["git", "-C", str(BOOK_REPO), "archive", BOOK_COMMIT], - check=True, capture_output=True, + check=True, + capture_output=True, ).stdout subprocess.run(["tar", "-x", "-C", str(BOOK_EXPORT)], input=archive, check=True) @@ -223,7 +226,8 @@ def build(args): md = path.read_text() counts = count_constructs(md) synthetic[path.stem] = { - "md": md, "counts": counts, + "md": md, + "counts": counts, "covers": {k for k, v in counts.items() if v}, } @@ -298,12 +302,15 @@ def main(): sub = p.add_subparsers(dest="cmd", required=True) for name, fn in (("build", build),): s = sub.add_parser(name) - s.add_argument("--converter", default=str(REPO), - help="folder that holds the converter module (default: %(default)s)") - s.add_argument("--installed", action="store_true", - help="import the converter from the Python environment, not from --converter") - s.add_argument("--module", default="md2misc", - help="module that exposes convert() (default: %(default)s)") + s.add_argument( + "--converter", default=str(REPO), help="folder that holds the converter module (default: %(default)s)" + ) + s.add_argument( + "--installed", + action="store_true", + help="import the converter from the Python environment, not from --converter", + ) + s.add_argument("--module", default="md2misc", help="module that exposes convert() (default: %(default)s)") s.set_defaults(fn=fn) args = p.parse_args() args.fn(args) diff --git a/tests/schelp_cases.py b/tests/schelp_cases.py index 5bd68b4..86bb785 100644 --- a/tests/schelp_cases.py +++ b/tests/schelp_cases.py @@ -24,8 +24,8 @@ ("![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), + ('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), ("> [!FOO]\n> An alert that is not known.\n", "alert of a kind that is not known", 1), @@ -54,85 +54,102 @@ M = "## Class methods\n\n" # Markdown that has no schelp form, which the converters take for text: only the check of the source stops at it. -SOURCE_ONLY = [ - ("* One\n* Two\n", "list with `*` or `+` marks", 1), - ("Text.\n\n+ One\n", "list with `*` or `+` marks", 3), - ("1) One\n2) Two\n", "numbered list with `)`", 1), - ("Above.\n\n***\n\nBelow.\n", "horizontal rule", 3), - ("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 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\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), - ("### *ar\n\n| a | | b |\n|---|---|---|\n| x | 1 | y |\n", "column without a heading", 3), - ("### *ar\n\n| a | b |\n|---|---|\n", "table without rows", 3), - ("### *ar\n\n| a | b |\n|---|---|\n\nText.\n", "table without rows", 3), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\nMore text.\n", "line without `|` after a table", 6), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y | z |\n", "more cells than the header", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n| w | v | u |\n", "more cells than the header", 6), - ("### *ar\n\n| a | b |\n|---|---|\n| two words | y |\n", "argument name `two words`", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| *ar | y |\n", "argument name `*ar`", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| 1x | y |\n", "argument name `1x`", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| **x** | y |\n", "argument name `**x**`", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| | y |\n", "argument name ``", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| `x | y |\n", "argument name", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n| `x` | z |\n", "argument `x` twice", 6), - ("### *ar\n\n| a | b |\n|---|---|\n| x | |\n", "argument `x` without text", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| x |\n", "argument `x` without text", 5), - ("### *ar\n\n| a | r | b |\n|---|---|---|\n| x | 1 |\n", "argument `x` without text", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| x | Code `a|b`. |\n", "`|` in code in a table", 5), - ("### *ar\n\n| `a|b` | c |\n|---|---|\n| x | y |\n", "`|` in code in a table", 3), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y \\\\| z |\n", "`\\\\|` in a table row", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\n| a | b |\n|---|---|\n| w | v |\n", "second table", 7), - ("### *ar\n\nReturns: x.\n\n| a | b |\n|---|---|\n| w | v |\n", "table after `Returns:`", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\nMore text.\n", "text after the argument table", 7), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n- A list.\n", "text after the argument table", 6), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\n```\nx = 1;\n```\n", "text after the argument table", 7), - ("### *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 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), +SOURCE_ONLY = ( + [ + ("* One\n* Two\n", "list with `*` or `+` marks", 1), + ("Text.\n\n+ One\n", "list with `*` or `+` marks", 3), + ("1) One\n2) Two\n", "numbered list with `)`", 1), + ("Above.\n\n***\n\nBelow.\n", "horizontal rule", 3), + ("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 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), ] -] + [ - ("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]: 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), -] + + [ + (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\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), + ("### *ar\n\n| a | | b |\n|---|---|---|\n| x | 1 | y |\n", "column without a heading", 3), + ("### *ar\n\n| a | b |\n|---|---|\n", "table without rows", 3), + ("### *ar\n\n| a | b |\n|---|---|\n\nText.\n", "table without rows", 3), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\nMore text.\n", "line without `|` after a table", 6), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y | z |\n", "more cells than the header", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n| w | v | u |\n", "more cells than the header", 6), + ("### *ar\n\n| a | b |\n|---|---|\n| two words | y |\n", "argument name `two words`", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| *ar | y |\n", "argument name `*ar`", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| 1x | y |\n", "argument name `1x`", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| **x** | y |\n", "argument name `**x**`", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| | y |\n", "argument name ``", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| `x | y |\n", "argument name", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n| `x` | z |\n", "argument `x` twice", 6), + ("### *ar\n\n| a | b |\n|---|---|\n| x | |\n", "argument `x` without text", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| x |\n", "argument `x` without text", 5), + ("### *ar\n\n| a | r | b |\n|---|---|---|\n| x | 1 |\n", "argument `x` without text", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| x | Code `a|b`. |\n", "`|` in code in a table", 5), + ("### *ar\n\n| `a|b` | c |\n|---|---|\n| x | y |\n", "`|` in code in a table", 3), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y \\\\| z |\n", "`\\\\|` in a table row", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\n| a | b |\n|---|---|\n| w | v |\n", "second table", 7), + ("### *ar\n\nReturns: x.\n\n| a | b |\n|---|---|\n| w | v |\n", "table after `Returns:`", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\nMore text.\n", "text after the argument table", 7), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n- A list.\n", "text after the argument table", 6), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\n```\nx = 1;\n```\n", "text after the argument table", 7), + ( + "### *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 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]: 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. WRITER_ONLY = [ @@ -183,7 +200,7 @@ "---\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", + '> 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 @@ -197,37 +214,63 @@ ("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
"]), + ( + "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:"']), + ( + "> 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 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."]), + ( + "> [!NOTE]\n> Try this:\n> ```\n> x = 1;\n> ```\n> And then this.\n", + ["", "And then this."], + ), ("It costs $5 and $10, and \\$x\\$ is not math.\n", ["It costs $5 and $10, and $x$ is not math."]), ("#1 is text.\n", ["

#1 is text."]), ("Math $a::b$ in text.\n", ["a::b"]), ("Before.\n\n$$\nx\n::\ny\n$$\n\nAfter.\n", ["x\n::\ny"]), ("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
"]), + ( + "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"]), + ( + "| A | |\n|---|---|\n| a \\|\\| b | `x \\| y` |\n", + ["Aa || bx | y"], + ), ] diff --git a/tests/schelp_fixtures.py b/tests/schelp_fixtures.py index 101d3d9..6c4de6d 100644 --- a/tests/schelp_fixtures.py +++ b/tests/schelp_fixtures.py @@ -19,6 +19,7 @@ python3 tests/schelp_fixtures.py update """ + import argparse import importlib import json @@ -153,7 +154,10 @@ def render_texts(sclang: str, texts: dict, timeout: int = 180, copied: list = No + "0.exit;\n" ) env = dict( - os.environ, HOME=str(tmp / "home"), XDG_DATA_HOME=str(data), XDG_CONFIG_HOME=str(data), + os.environ, + HOME=str(tmp / "home"), + XDG_DATA_HOME=str(data), + XDG_CONFIG_HOME=str(data), QT_QPA_PLATFORM="offscreen", ) done = subprocess.run([sclang, str(script)], env=env, capture_output=True, text=True, timeout=timeout) @@ -192,8 +196,11 @@ def render_all(sclang: str, timeout: int = 180) -> dict: 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) + 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)) diff --git a/tests/test_schelp_behavior.py b/tests/test_schelp_behavior.py index 4fc6617..ad42a25 100644 --- a/tests/test_schelp_behavior.py +++ b/tests/test_schelp_behavior.py @@ -2,6 +2,7 @@ How the schelp output is made, for the cases that the fixtures do not show: header values, special sections, admonitions, math, code, insertion points and quotation marks. """ + import pytest from md2misc import convert_schelp @@ -61,7 +62,7 @@ def test_metadata_lists_are_a_string_with_commas_or_a_list(value): ('summary: "Quoted: with a colon"', "SUMMARY::Quoted: with a colon\n"), ("summary: 'Single quoted'", "SUMMARY::Single quoted\n"), ("summary: Unquoted: with a colon", "SUMMARY::Unquoted: with a colon\n"), - ('related: ["Classes/A", \'Classes/B\']', "RELATED::Classes/A, Classes/B\n"), + ("related: [\"Classes/A\", 'Classes/B']", "RELATED::Classes/A, Classes/B\n"), ("related: Classes/A, Classes/B", "RELATED::Classes/A, Classes/B\n"), ('categories:\n - "A"\n - B', "CATEGORIES::A, B\n"), ], @@ -109,16 +110,19 @@ def test_header_without_title_or_class_is_an_error(): # ------------------------------------------------------ special sections -@pytest.mark.parametrize("heading, expected", [ - ("## Description", "DESCRIPTION::"), - ("## description", "DESCRIPTION::"), - ("## Examples", "EXAMPLES::"), - ("## EXAMPLES", "EXAMPLES::"), - ("## Other", "SECTION::Other"), - ("### Description", "SUBSECTION::Description"), - ("#### Examples", "SUBSUBSECTION::Examples"), - ("##### Deeper", "SUBSUBSECTION::Deeper"), -]) +@pytest.mark.parametrize( + "heading, expected", + [ + ("## Description", "DESCRIPTION::"), + ("## description", "DESCRIPTION::"), + ("## Examples", "EXAMPLES::"), + ("## EXAMPLES", "EXAMPLES::"), + ("## Other", "SECTION::Other"), + ("### Description", "SUBSECTION::Description"), + ("#### Examples", "SUBSUBSECTION::Examples"), + ("##### Deeper", "SUBSUBSECTION::Deeper"), + ], +) def test_headings(heading, expected): assert convert_schelp(heading + "\n") == expected + "\n" @@ -126,10 +130,18 @@ def test_headings(heading, expected): # ------------------------------------------------------------ admonitions -@pytest.mark.parametrize("mark, tag", [ - ("NOTE", "note"), ("TIP", "note"), ("IMPORTANT", "note"), ("WARNING", "warning"), ("CAUTION", "warning"), - ("note", "note"), ("Warning", "warning"), -]) +@pytest.mark.parametrize( + "mark, tag", + [ + ("NOTE", "note"), + ("TIP", "note"), + ("IMPORTANT", "note"), + ("WARNING", "warning"), + ("CAUTION", "warning"), + ("note", "note"), + ("Warning", "warning"), + ], +) def test_admonition_tags(mark, tag): assert convert_schelp(f"> [!{mark}]\n> The text.\n") == f"{tag}::\nThe text.\n\n::\n" @@ -218,15 +230,18 @@ def test_insertion_point_inside_a_line_is_an_html_comment(): # ------------------------------------------------------------ inline tags -@pytest.mark.parametrize("markdown, expected", [ - ("**Note:** text.", "strong::Note: :: text."), - ("*Note:* text.", "emphasis::Note: :: text."), - ("Use `foo:` here.", "Use code::foo: :: here."), - ("Use `C:\\` here.", "Use code::C:\\ :: here."), - ("[Note:](https://example.com) text.", "link::https://example.com##Note: :: text."), - ("Math $a:$ here.", "Math math::a: :: here."), - ("Text.[^1]\n\n[^1]: Ends:", "Text.footnote::Ends: ::"), -]) +@pytest.mark.parametrize( + "markdown, expected", + [ + ("**Note:** text.", "strong::Note: :: text."), + ("*Note:* text.", "emphasis::Note: :: text."), + ("Use `foo:` here.", "Use code::foo: :: here."), + ("Use `C:\\` here.", "Use code::C:\\ :: here."), + ("[Note:](https://example.com) text.", "link::https://example.com##Note: :: text."), + ("Math $a:$ here.", "Math math::a: :: here."), + ("Text.[^1]\n\n[^1]: Ends:", "Text.footnote::Ends: ::"), + ], +) def test_inline_tag_with_a_colon_or_backslash_at_the_end_gets_a_space(markdown, expected): # SCDoc takes the character as part of the end-tag `::` assert convert_schelp(markdown + "\n") == expected + "\n" @@ -268,15 +283,19 @@ 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"]) +@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 diff --git a/tests/test_schelp_citations.py b/tests/test_schelp_citations.py index 8b1ce7b..e0a4020 100644 --- a/tests/test_schelp_citations.py +++ b/tests/test_schelp_citations.py @@ -3,6 +3,7 @@ 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 @@ -11,45 +12,51 @@ 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::") +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"]) +@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") + assert out == (f"One footnote::{DOE}.::. Two footnote::Doe 1999, 31.::. 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") + 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") + assert out == (f"Text.footnote::As in (Doe 1999, 30).\n\nAnd (Smith and Lee 2000).:: More footnote::{SMITH}.::.\n") def test_citation_directly_after_a_word(pandoc): @@ -98,8 +105,9 @@ def test_text_without_citations_does_not_need_the_bibliography(monkeypatch): 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"): + with pytest.raises( + UnsupportedConstruct, match="give a bibliography to the conversion, or write the citation as text" + ): convert_schelp("A text [@doe1999].\n") diff --git a/tests/test_schelp_errors.py b/tests/test_schelp_errors.py index 9108ec4..5a2da0a 100644 --- a/tests/test_schelp_errors.py +++ b/tests/test_schelp_errors.py @@ -2,6 +2,7 @@ Markdown that has no schelp form stops the conversion: `convert_schelp` raises an error that holds the construct and its line, and `describe()` names the file too. Markdown that only looks like such a construct is accepted. """ + import re import pytest @@ -25,12 +26,15 @@ def test_error_names_the_file_and_the_line(): with pytest.raises(UnsupportedConstruct) as error: 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: horizontal rule" + assert ( + error.value.describe("page.md") + == "page.md:3: the schelp output cannot write this Markdown construct: horizontal rule" + ) -@pytest.mark.parametrize("markdown, metadata, insertions, message", DOCUMENT_ERRORS, - ids=[m for *_, m in DOCUMENT_ERRORS]) +@pytest.mark.parametrize( + "markdown, metadata, insertions, message", DOCUMENT_ERRORS, ids=[m for *_, m in DOCUMENT_ERRORS] +) def test_document_error_stops_the_conversion(markdown, metadata, insertions, message): with pytest.raises((DocumentError, UnsupportedConstruct)) as error: convert_schelp(markdown, metadata, insertions) diff --git a/tests/test_schelp_golden.py b/tests/test_schelp_golden.py index f941cdc..d329ee6 100644 --- a/tests/test_schelp_golden.py +++ b/tests/test_schelp_golden.py @@ -2,6 +2,7 @@ The schelp output has not changed: every fixture in tests/schelp is converted and compared with the .schelp file next to it. """ + import pytest from schelp_fixtures import convert, fixtures, needs_pandoc diff --git a/tests/test_schelp_methods.py b/tests/test_schelp_methods.py index 3c1a01c..8ef9c3c 100644 --- a/tests/test_schelp_methods.py +++ b/tests/test_schelp_methods.py @@ -3,6 +3,7 @@ gives `METHOD::`, the rows of the argument table of a method give `ARGUMENT::` entries, and a `Returns:` paragraph gives `returns::`. The checks that stop the conversion are in schelp_cases.py. """ + import re import pytest @@ -28,15 +29,18 @@ def arguments(schelp: str) -> list: def test_method_with_an_argument_table_and_a_return_value(): out = methods("### *ar\n\n" + TABLE + "\nReturns: one channel.\n\n## Examples\n\nText.\n") - assert out == ("CLASSMETHODS::\n\nMETHOD::ar\n\n" - "ARGUMENT::freq\nThe frequency.\n\nARGUMENT::amp\nThe level.\n\n" - "returns::one channel.\n\nEXAMPLES::\n\nText.\n") + assert out == ( + "CLASSMETHODS::\n\nMETHOD::ar\n\n" + "ARGUMENT::freq\nThe frequency.\n\nARGUMENT::amp\nThe level.\n\n" + "returns::one channel.\n\nEXAMPLES::\n\nText.\n" + ) def test_methods_without_tables_and_text_before_the_first_method(): out = methods("Intro.\n\n### *ar, *kr\n\nText.\n\nReturns: two\nchannels.\n\n### *new\n\nMakes one.\n") - assert out == ("CLASSMETHODS::\n\nIntro.\n\nMETHOD::ar, kr\n\nText.\n\nreturns::two\nchannels.\n\n" - "METHOD::new\n\nMakes one.\n") + assert out == ( + "CLASSMETHODS::\n\nIntro.\n\nMETHOD::ar, kr\n\nText.\n\nreturns::two\nchannels.\n\nMETHOD::new\n\nMakes one.\n" + ) def test_text_of_a_method_comes_before_its_arguments(): @@ -47,8 +51,13 @@ def test_text_of_a_method_comes_before_its_arguments(): def test_two_methods_with_tables(): out = methods("### *ar\n\n" + TABLE + "\n### *kr\n\n" + TABLE.replace("freq", "rate")) assert re.findall(r"^(METHOD|ARGUMENT)::(.*)$", out, re.M) == [ - ("METHOD", "ar"), ("ARGUMENT", "freq"), ("ARGUMENT", "amp"), - ("METHOD", "kr"), ("ARGUMENT", "rate"), ("ARGUMENT", "amp")] + ("METHOD", "ar"), + ("ARGUMENT", "freq"), + ("ARGUMENT", "amp"), + ("METHOD", "kr"), + ("ARGUMENT", "rate"), + ("ARGUMENT", "amp"), + ] def test_section_heading_is_not_case_sensitive(): @@ -61,10 +70,18 @@ def test_next_level_2_heading_ends_the_section(): assert "SECTION::More\n\nReturns: text, as it is not in a method." in out -@pytest.mark.parametrize("heading, names", [ - ("### *ar", "ar"), ("### *ar, *kr", "ar, kr"), ("### *ar,*kr", "ar, kr"), ("### *ar , *kr ", "ar, kr"), - ("### *new_2", "new_2"), ("### *ar, *kr, *new", "ar, kr, new"), -], ids=["one name", "two names", "no space", "more spaces", "underscore and digit", "three names"]) +@pytest.mark.parametrize( + "heading, names", + [ + ("### *ar", "ar"), + ("### *ar, *kr", "ar, kr"), + ("### *ar,*kr", "ar, kr"), + ("### *ar , *kr ", "ar, kr"), + ("### *new_2", "new_2"), + ("### *ar, *kr, *new", "ar, kr, new"), + ], + ids=["one name", "two names", "no space", "more spaces", "underscore and digit", "three names"], +) def test_method_headings(heading, names): assert f"METHOD::{names}\n" in methods(heading + "\n\nText.\n") @@ -72,21 +89,35 @@ def test_method_headings(heading, names): # ---------------------------------------------------- forms of the argument table -@pytest.mark.parametrize("table", [ - TABLE, - "Argument | Text\n---|---\nfreq | The frequency.\namp | The level.\n", - "| Argument | Text\n|---|---\n| freq | The frequency.\n| amp | The level.\n", - "Argument | Text |\n---|---|\nfreq | The frequency. |\namp | The level. |\n", - "| Argument | Text |\n---|---\nfreq | The frequency. |\n| amp | The level.\n", - "|Argument|Text|\n|-|-|\n|freq|The frequency.|\n|amp|The level.|\n", - "| Argument | Text |\n|:---|---:|\n| freq | The frequency. |\n| amp | The level. |\n", - "| Argument | Text |\n| :---: | :-- |\n| freq | The frequency. |\n| amp | The level. |\n", - " | Argument | Text |\n |---|---|\n | freq | The frequency. |\n | amp | The level. |\n", - "| Argument | Text |\n|---|---|\n|\tfreq\t| The frequency. |\n| amp | The level. | \n", - "| `Argument` | **Text** |\n|---|---|\n| freq | The frequency. |\n| amp | The level. |\n", -], ids=["outer pipes", "no outer pipes", "leading pipes only", "trailing pipes only", "mixed pipes", - "no spaces", "alignment colons", "spaces in the delimiter row", "indent of 3", "spaces and tabs", - "markup in the header"]) +@pytest.mark.parametrize( + "table", + [ + TABLE, + "Argument | Text\n---|---\nfreq | The frequency.\namp | The level.\n", + "| Argument | Text\n|---|---\n| freq | The frequency.\n| amp | The level.\n", + "Argument | Text |\n---|---|\nfreq | The frequency. |\namp | The level. |\n", + "| Argument | Text |\n---|---\nfreq | The frequency. |\n| amp | The level.\n", + "|Argument|Text|\n|-|-|\n|freq|The frequency.|\n|amp|The level.|\n", + "| Argument | Text |\n|:---|---:|\n| freq | The frequency. |\n| amp | The level. |\n", + "| Argument | Text |\n| :---: | :-- |\n| freq | The frequency. |\n| amp | The level. |\n", + " | Argument | Text |\n |---|---|\n | freq | The frequency. |\n | amp | The level. |\n", + "| Argument | Text |\n|---|---|\n|\tfreq\t| The frequency. |\n| amp | The level. | \n", + "| `Argument` | **Text** |\n|---|---|\n| freq | The frequency. |\n| amp | The level. |\n", + ], + ids=[ + "outer pipes", + "no outer pipes", + "leading pipes only", + "trailing pipes only", + "mixed pipes", + "no spaces", + "alignment colons", + "spaces in the delimiter row", + "indent of 3", + "spaces and tabs", + "markup in the header", + ], +) def test_forms_of_the_table_give_the_same_arguments(table): assert arguments(methods("### *ar\n\n" + table)) == ARGUMENTS @@ -98,10 +129,17 @@ def test_table_directly_after_a_paragraph_line(): assert arguments(out) == ARGUMENTS -@pytest.mark.parametrize("after", ["\n## Examples\n", "## Examples\n", "\nReturns: x.\n", "\n### *kr\n", - "### *kr\n"], - ids=["section after an empty line", "section directly after", "return value", - "method after an empty line", "method directly after"]) +@pytest.mark.parametrize( + "after", + ["\n## Examples\n", "## Examples\n", "\nReturns: x.\n", "\n### *kr\n", "### *kr\n"], + ids=[ + "section after an empty line", + "section directly after", + "return value", + "method after an empty line", + "method directly after", + ], +) def test_what_can_follow_the_table(after): assert arguments(methods("### *ar\n\n" + TABLE + after)) == ARGUMENTS @@ -121,35 +159,55 @@ def test_argument_names_with_underscores_and_digits(name): assert arguments(out) == [(name, "A.")] -@pytest.mark.parametrize("cell, text", [ - ("Uses `In.ar`.", "Uses code::In.ar::."), - ("A **loud** sound.", "A strong::loud:: sound."), - ("An *odd* one.", "An emphasis::odd:: one."), - ("See [SinOsc](sc:Classes/SinOsc).", "See link::Classes/SinOsc::."), - ("See [the site](https://example.com).", "See link::https://example.com##the site::."), - ("One \\| two.", "One | two."), - ("Code `a \\| b`.", "Code code::a | b::."), - ("A \\|\\| B.", "A \\|| B."), - ("Tag:: and ## here.", "Tag\\:: and \\## here."), - ("> 0 is on.", "> 0 is on."), - ("- 1 is off.", "- 1 is off."), - ("1. is first.", "1. is first."), - ("# is a sign.", "# is a sign."), - ("βˆ’1 to 1, β‰₯ 0.5.", "βˆ’1 to 1, β‰₯ 0.5."), - ("Math $x^2$.", "Math math::x^2::."), -], ids=["code", "bold", "italic", "sc link", "web link", "escaped pipe", "escaped pipe in code", - "two escaped pipes", "schelp marks", "quote mark", "list mark", "number mark", "heading mark", - "not ASCII", "math"]) +@pytest.mark.parametrize( + "cell, text", + [ + ("Uses `In.ar`.", "Uses code::In.ar::."), + ("A **loud** sound.", "A strong::loud:: sound."), + ("An *odd* one.", "An emphasis::odd:: one."), + ("See [SinOsc](sc:Classes/SinOsc).", "See link::Classes/SinOsc::."), + ("See [the site](https://example.com).", "See link::https://example.com##the site::."), + ("One \\| two.", "One | two."), + ("Code `a \\| b`.", "Code code::a | b::."), + ("A \\|\\| B.", "A \\|| B."), + ("Tag:: and ## here.", "Tag\\:: and \\## here."), + ("> 0 is on.", "> 0 is on."), + ("- 1 is off.", "- 1 is off."), + ("1. is first.", "1. is first."), + ("# is a sign.", "# is a sign."), + ("βˆ’1 to 1, β‰₯ 0.5.", "βˆ’1 to 1, β‰₯ 0.5."), + ("Math $x^2$.", "Math math::x^2::."), + ], + ids=[ + "code", + "bold", + "italic", + "sc link", + "web link", + "escaped pipe", + "escaped pipe in code", + "two escaped pipes", + "schelp marks", + "quote mark", + "list mark", + "number mark", + "heading mark", + "not ASCII", + "math", + ], +) def test_text_of_an_argument(cell, text): out = methods(f"### *ar\n\n| Argument | Text |\n|---|---|\n| x | {cell} |\n") assert arguments(out) == [("x", text)] def test_columns_between_the_name_and_the_text(): - table = ("| Argument | Range | Unit | Text |\n|---|---|---|---|\n" - "| freq | 20 to 20000 | Hz | The frequency. |\n" - "| amp | | | The level. |\n" - "| pan | βˆ’1 to 1 | | The position. |\n") + table = ( + "| Argument | Range | Unit | Text |\n|---|---|---|---|\n" + "| freq | 20 to 20000 | Hz | The frequency. |\n" + "| amp | | | The level. |\n" + "| pan | βˆ’1 to 1 | | The position. |\n" + ) assert arguments(methods("### *ar\n\n" + table)) == [ ("freq", "The frequency.\nRange: 20 to 20000\nUnit: Hz"), ("amp", "The level."), @@ -165,21 +223,29 @@ def test_markup_in_the_other_columns(): # ------------------------------------------------------------- the return value -@pytest.mark.parametrize("paragraph, returns", [ - ("Returns: one channel.", "returns::one channel."), - ("Returns:one channel.", "returns::one channel."), - ("Returns: an `Array`, two\nchannels.", "returns::an code::Array::, two\nchannels."), -], ids=["one line", "no space", "markup and two lines"]) +@pytest.mark.parametrize( + "paragraph, returns", + [ + ("Returns: one channel.", "returns::one channel."), + ("Returns:one channel.", "returns::one channel."), + ("Returns: an `Array`, two\nchannels.", "returns::an code::Array::, two\nchannels."), + ], + ids=["one line", "no space", "markup and two lines"], +) def test_return_value(paragraph, returns): assert returns in methods("### *ar\n\n" + TABLE + "\n" + paragraph + "\n") -@pytest.mark.parametrize("markdown", [ - "## Class methods\n\nReturns: before a method.\n", - "## Description\n\nReturns: in another section.\n", - "## Class methods\n\n### *ar\n\nThe text. Returns: in a paragraph.\n", - "## Class methods\n\n### *ar\n\nThe text.\nReturns: on the second line of a paragraph.\n", -], ids=["before a method", "in another section", "in the text", "second line of a paragraph"]) +@pytest.mark.parametrize( + "markdown", + [ + "## Class methods\n\nReturns: before a method.\n", + "## Description\n\nReturns: in another section.\n", + "## Class methods\n\n### *ar\n\nThe text. Returns: in a paragraph.\n", + "## Class methods\n\n### *ar\n\nThe text.\nReturns: on the second line of a paragraph.\n", + ], + ids=["before a method", "in another section", "in the text", "second line of a paragraph"], +) def test_returns_that_is_text(markdown): out = convert_schelp(markdown) assert "returns::" not in out @@ -190,17 +256,18 @@ def test_returns_that_is_text(markdown): 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") + 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") + 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\nINSTANCEMETHODS::\n\nMETHOD::free\n\nFrees it.\n") def test_instance_method_heading_outside_a_methods_section_is_a_heading(): @@ -210,8 +277,11 @@ def test_instance_method_heading_outside_a_methods_section_is_a_heading(): # ------------------------------------------------------------------ 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"]) +@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") @@ -219,8 +289,10 @@ def test_discussion(before): 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") + 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 diff --git a/tests/test_schelp_render.py b/tests/test_schelp_render.py index 17d6b16..b234021 100644 --- a/tests/test_schelp_render.py +++ b/tests/test_schelp_render.py @@ -5,6 +5,7 @@ All versions of sclang must parse the output with no error and give the expected parts of the pages. Only the version that made the .html files must give the same whole pages. """ + import re import pytest diff --git a/tests/test_schelp_tables.py b/tests/test_schelp_tables.py index 98cd168..0c683ee 100644 --- a/tests/test_schelp_tables.py +++ b/tests/test_schelp_tables.py @@ -2,34 +2,51 @@ 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"]) +@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"]) +@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" diff --git a/tests/test_schelp_writer.py b/tests/test_schelp_writer.py index a8fa76a..c10afff 100644 --- a/tests/test_schelp_writer.py +++ b/tests/test_schelp_writer.py @@ -2,6 +2,7 @@ The writers of the schelp backend stop at the constructs that have no schelp form, too, if the check of the Markdown source does not find them first. The error has no line then. """ + import pytest from md2misc import convert_schelp diff --git a/tests/test_tables.py b/tests/test_tables.py index 3a3af48..1dfa0b2 100644 --- a/tests/test_tables.py +++ b/tests/test_tables.py @@ -3,6 +3,7 @@ table ends. The expected values are those of cmark-gfm 0.29.0.gfm.13, the GitHub Flavored Markdown parser of GitHub, where the comments do not say otherwise (checked on 2026-11-17). """ + import pytest from md2misc import tables @@ -15,70 +16,112 @@ def table(markdown: str): if tables.starts_table(lines, number): header = tables.split_row(lines[number]) rows = [header] - for row in lines[number + 2:tables.table_end(lines, number)]: + for row in lines[number + 2 : tables.table_end(lines, number)]: cells = tables.split_row(row) rows.append(cells + [""] * (len(header) - len(cells))) return rows return None -@pytest.mark.parametrize("markdown, rows", [ - ("| a | b |\n|---|---|\n| 1 | 2 |\n", [["a", "b"], ["1", "2"]]), - ("a | b\n---|---\n1 | 2\n", [["a", "b"], ["1", "2"]]), - ("| a | b\n|--|--\n| 1 | 2\n", [["a", "b"], ["1", "2"]]), - ("a | b |\n--|--|\n1 | 2 |\n", [["a", "b"], ["1", "2"]]), - ("| abc | defghi |\n:-: | -----------:\nbar | baz\n", [["abc", "defghi"], ["bar", "baz"]]), - ("|a|b|\n|-|-|\n|1|2|\n", [["a", "b"], ["1", "2"]]), - ("|a|b|c|d|\n|:--|:-:|--:|---|\n|1|2|3|4|\n", [["a", "b", "c", "d"], ["1", "2", "3", "4"]]), - ("|a|b|\n| :---: | ---: |\n|1|2|\n", [["a", "b"], ["1", "2"]]), - ("|a|b| \n|-|-| \n|1|2| \n", [["a", "b"], ["1", "2"]]), - (" |a|b|\n |-|-|\n |1|2|\n", [["a", "b"], ["1", "2"]]), -], ids=["outer pipes", "no outer pipes", "leading pipes only", "trailing pipes only", "mixed outer pipes", - "one hyphen", "alignment", "spaces around delimiter cells", "trailing spaces", "indent of 3"]) +@pytest.mark.parametrize( + "markdown, rows", + [ + ("| a | b |\n|---|---|\n| 1 | 2 |\n", [["a", "b"], ["1", "2"]]), + ("a | b\n---|---\n1 | 2\n", [["a", "b"], ["1", "2"]]), + ("| a | b\n|--|--\n| 1 | 2\n", [["a", "b"], ["1", "2"]]), + ("a | b |\n--|--|\n1 | 2 |\n", [["a", "b"], ["1", "2"]]), + ("| abc | defghi |\n:-: | -----------:\nbar | baz\n", [["abc", "defghi"], ["bar", "baz"]]), + ("|a|b|\n|-|-|\n|1|2|\n", [["a", "b"], ["1", "2"]]), + ("|a|b|c|d|\n|:--|:-:|--:|---|\n|1|2|3|4|\n", [["a", "b", "c", "d"], ["1", "2", "3", "4"]]), + ("|a|b|\n| :---: | ---: |\n|1|2|\n", [["a", "b"], ["1", "2"]]), + ("|a|b| \n|-|-| \n|1|2| \n", [["a", "b"], ["1", "2"]]), + (" |a|b|\n |-|-|\n |1|2|\n", [["a", "b"], ["1", "2"]]), + ], + ids=[ + "outer pipes", + "no outer pipes", + "leading pipes only", + "trailing pipes only", + "mixed outer pipes", + "one hyphen", + "alignment", + "spaces around delimiter cells", + "trailing spaces", + "indent of 3", + ], +) def test_forms_of_a_table(markdown, rows): assert table(markdown) == rows -@pytest.mark.parametrize("markdown", [ - "|a|b|\n|- -|---|\n|1|2|\n", - "|a|b|\n|:|---|\n", - "|a|b|\n|=|=|\n", - "|a|b|\n|-||\n", - "|a|\n---\n|1|\n", - " |a|b|\n |-|-|\n |1|2|\n", - "|a|b|\n |-|-|\n|1|2|\n", - "|a|b|\n\n|-|-|\n|1|2|\n", - "| a | b |\n| --- \\|| --- |\n", - "- a | b\n- c | d\n", - "a | b\n--- ---\n", - "Text without a pipe.\n---|---\n", -], ids=["space in a delimiter cell", "colon only", "equals signs", "empty delimiter cell", - "delimiter row without a pipe (a heading)", "indent of 4 (code)", "delimiter row with an indent of 4", - "empty line after the header", "escaped pipe in the delimiter row", "list items with pipes", - "delimiter row without pipes", "header without a pipe"]) +@pytest.mark.parametrize( + "markdown", + [ + "|a|b|\n|- -|---|\n|1|2|\n", + "|a|b|\n|:|---|\n", + "|a|b|\n|=|=|\n", + "|a|b|\n|-||\n", + "|a|\n---\n|1|\n", + " |a|b|\n |-|-|\n |1|2|\n", + "|a|b|\n |-|-|\n|1|2|\n", + "|a|b|\n\n|-|-|\n|1|2|\n", + "| a | b |\n| --- \\|| --- |\n", + "- a | b\n- c | d\n", + "a | b\n--- ---\n", + "Text without a pipe.\n---|---\n", + ], + ids=[ + "space in a delimiter cell", + "colon only", + "equals signs", + "empty delimiter cell", + "delimiter row without a pipe (a heading)", + "indent of 4 (code)", + "delimiter row with an indent of 4", + "empty line after the header", + "escaped pipe in the delimiter row", + "list items with pipes", + "delimiter row without pipes", + "header without a pipe", + ], +) def test_not_a_table(markdown): assert table(markdown) is None -@pytest.mark.parametrize("markdown, rows", [ - ("|a|\n|---|\n|1|\n", [["a"], ["1"]]), - ("a |\n--|\n1 |\n", [["a"], ["1"]]), - ("| a\n|--\n| 1\n", [["a"], ["1"]]), - ("||\n|-|\n|1|\n", [[""], ["1"]]), -], ids=["outer pipes", "trailing pipes", "leading pipes", "empty header"]) +@pytest.mark.parametrize( + "markdown, rows", + [ + ("|a|\n|---|\n|1|\n", [["a"], ["1"]]), + ("a |\n--|\n1 |\n", [["a"], ["1"]]), + ("| a\n|--\n| 1\n", [["a"], ["1"]]), + ("||\n|-|\n|1|\n", [[""], ["1"]]), + ], + ids=["outer pipes", "trailing pipes", "leading pipes", "empty header"], +) def test_one_column(markdown, rows): assert table(markdown) == rows -@pytest.mark.parametrize("markdown, rows", [ - ("|a|b|\n|-|-|\n", [["a", "b"]]), - ("|a|b|\n|-|-|\n|1|\n", [["a", "b"], ["1", ""]]), - ("|a|b|\n|-|-|\n||2|\n|1||\n", [["a", "b"], ["", "2"], ["1", ""]]), - ("| a | b |\n|-|-|\n| 1 |\t2\t|\n", [["a", "b"], ["1", "2"]]), - ("| | |\n|-|-|\n|1|2|\n", [["", ""], ["1", "2"]]), - ("| name | range |\n|---|---|\n| pan | βˆ’1 to 1 |\n", [["name", "range"], ["pan", "βˆ’1 to 1"]]), -], ids=["header only", "short row padded", "empty cells", "spaces and tabs trimmed", "empty header cells", - "text that is not ASCII"]) +@pytest.mark.parametrize( + "markdown, rows", + [ + ("|a|b|\n|-|-|\n", [["a", "b"]]), + ("|a|b|\n|-|-|\n|1|\n", [["a", "b"], ["1", ""]]), + ("|a|b|\n|-|-|\n||2|\n|1||\n", [["a", "b"], ["", "2"], ["1", ""]]), + ("| a | b |\n|-|-|\n| 1 |\t2\t|\n", [["a", "b"], ["1", "2"]]), + ("| | |\n|-|-|\n|1|2|\n", [["", ""], ["1", "2"]]), + ("| name | range |\n|---|---|\n| pan | βˆ’1 to 1 |\n", [["name", "range"], ["pan", "βˆ’1 to 1"]]), + ], + ids=[ + "header only", + "short row padded", + "empty cells", + "spaces and tabs trimmed", + "empty header cells", + "text that is not ASCII", + ], +) def test_cells(markdown, rows): assert table(markdown) == rows @@ -99,12 +142,16 @@ def test_delimiter_row_with_another_number_of_cells_starts_a_table(): assert table("|a|b|\n|---|---|---|\n|1|2|\n") == [["a", "b"], ["1", "2"]] -@pytest.mark.parametrize("row, cells", [ - ("|x\\|y|2|", ["x\\|y", "2"]), - ("|`x\\|y`|2|", ["`x\\|y`", "2"]), - ("|1|2\\|", ["1", "2\\|"]), - ("|`x|y`|2|", ["`x", "y`", "2"]), -], ids=["escaped pipe", "escaped pipe in code", "escaped pipe at the end", "pipe in code splits the cell"]) +@pytest.mark.parametrize( + "row, cells", + [ + ("|x\\|y|2|", ["x\\|y", "2"]), + ("|`x\\|y`|2|", ["`x\\|y`", "2"]), + ("|1|2\\|", ["1", "2\\|"]), + ("|`x|y`|2|", ["`x", "y`", "2"]), + ], + ids=["escaped pipe", "escaped pipe in code", "escaped pipe at the end", "pipe in code splits the cell"], +) def test_split_row_with_pipes_in_cells(row, cells): assert tables.split_row(row) == cells @@ -114,9 +161,20 @@ def test_unescape_gives_the_pipe(): assert tables.unescape("`x\\|y`") == "`x|y`" -@pytest.mark.parametrize("after", ["", "\n\nnext", "\n# H", "\n> q", "\n```\nx\n```", "\n- x", "\n1. x", "\n***"], - ids=["end of the text", "empty line", "heading", "block quote", "code block", "list", - "numbered list", "horizontal rule"]) +@pytest.mark.parametrize( + "after", + ["", "\n\nnext", "\n# H", "\n> q", "\n```\nx\n```", "\n- x", "\n1. x", "\n***"], + ids=[ + "end of the text", + "empty line", + "heading", + "block quote", + "code block", + "list", + "numbered list", + "horizontal rule", + ], +) def test_end_of_a_table(after): lines = ("|a|b|\n|-|-|\n|1|2|" + after).split("\n") assert tables.table_end(lines, 0) == 3 @@ -132,11 +190,15 @@ def test_second_delimiter_row_is_a_row(): assert table("|a|b|\n|-|-|\n|1|2|\n|-|-|\n") == [["a", "b"], ["1", "2"], ["-", "-"]] -@pytest.mark.parametrize("markdown, header", [ - ("para\n|a|b|\n|-|-|\n|1|2|\n", 1), - ("p1\np2\n|a|b|\n|-|-|\n", 2), - ("|a|\n|b|\n|-|\n", 1), -], ids=["after a paragraph line", "after two paragraph lines", "only one header row"]) +@pytest.mark.parametrize( + "markdown, header", + [ + ("para\n|a|b|\n|-|-|\n|1|2|\n", 1), + ("p1\np2\n|a|b|\n|-|-|\n", 2), + ("|a|\n|b|\n|-|\n", 1), + ], + ids=["after a paragraph line", "after two paragraph lines", "only one header row"], +) def test_header_is_the_line_before_the_delimiter_row(markdown, header): lines = markdown.split("\n") assert [n for n in range(len(lines)) if tables.starts_table(lines, n)] == [header] diff --git a/tests/test_tex_battery.py b/tests/test_tex_battery.py index 2617c89..9e1db8a 100644 --- a/tests/test_tex_battery.py +++ b/tests/test_tex_battery.py @@ -3,6 +3,7 @@ .tex file that md2tex wrote for it. name@variant.tex is the Markdown of name.md with the convert() arguments from name@variant.args. See battery.py for how the fixtures are made. """ + import json import pytest diff --git a/tests/test_tex_library.py b/tests/test_tex_library.py index 6ef330a..8212d14 100644 --- a/tests/test_tex_library.py +++ b/tests/test_tex_library.py @@ -1,6 +1,7 @@ """ The TeX backend as a library: the arguments of `convert`, the default template, the warnings and the errors. """ + import subprocess import sys from pathlib import Path @@ -36,8 +37,9 @@ def test_unnumbered_headings(): def test_override_language_gives_every_code_block_the_language(): markdown = "```python\nx = 1\n```\n" assert "\\begin{minted}{python}" in convert(markdown) - assert "\\begin{minted}{supercollider}" in convert(markdown, minted_language="supercollider", - override_language=True) + assert "\\begin{minted}{supercollider}" in convert( + markdown, minted_language="supercollider", override_language=True + ) def test_default_template_has_the_tokens_for_the_body_and_the_document_class(): From e647de83979c69159a85af0e02ed97debda006cb Mon Sep 17 00:00:00 2001 From: Anders Eskildsen <22001464+aeskildsen@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:10:20 +0100 Subject: [PATCH 3/5] chore: fix ruff and basedpyright findings; check them in CI Add `pyrightconfig.json`, the `lint` script of `just lint` and a CI job. Fix the findings with changes to annotations and to the form of the code. The output and the errors of the conversions do not change. --- .github/workflows/tests.yml | 11 +++++++ CLAUDE.md | 1 + docs/development.md | 4 +-- just/project/lint.sh | 15 +++++++++ md2misc/backends/base.py | 40 +++++++++++++++++++--- md2misc/backends/schelp.py | 12 ++++--- md2misc/backends/tex.py | 10 +++--- md2misc/converters.py | 66 +++++++++++++++++++++---------------- md2misc/core.py | 16 ++++----- md2misc/errors_warnings.py | 5 ++- md2misc/helpers.py | 6 ++-- pyrightconfig.json | 4 +++ ruff.toml | 2 ++ tests/battery.py | 16 +++++---- tests/schelp_fixtures.py | 4 +-- 15 files changed, 145 insertions(+), 67 deletions(-) create mode 100644 just/project/lint.sh create mode 100644 pyrightconfig.json diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 2cd0e68..9906fce 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -6,6 +6,17 @@ on: pull_request: jobs: + # ruff and basedpyright, with the Python that the package needs at least. + lint: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: python -m pip install -e ".[test]" + - run: bash just/project/lint.sh + # 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. diff --git a/CLAUDE.md b/CLAUDE.md index 2a3a8bd..2b1491b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,6 +5,7 @@ Markdown to TeX (the same output as md2tex) and to SuperCollider help (schelp). ## Tests - There is no Nix tooling: the package is `pyproject.toml` only. The tests run in `.venv`, made in the `dev` distrobox with the Python of Ubuntu (in the container, `python3` on `PATH` is the Nix one of the host): `distrobox enter dev -- fish -lc 'cd ; and uv venv --python /usr/bin/python3 .venv; and uv pip install --python .venv/bin/python -e ".[test]"'`. Then `distrobox enter dev -- fish -lc 'cd ; and .venv/bin/python -m pytest'`. `` is the folder of this repository. +- Before you finish a change, run `just lint` in the same way as the tests (`just lint correct` also formats). - 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. diff --git a/docs/development.md b/docs/development.md index fef958a..0499e63 100644 --- a/docs/development.md +++ b/docs/development.md @@ -8,7 +8,7 @@ The [`just`](https://just.systems) recipes run the common tasks. Activate the vi |---|---| | `just check` | `just test` | | `just test` | all tests (`pytest`) | -| `just lint` | `actionlint` | +| `just lint` | `actionlint`, `ruff check`, `ruff format --check` and `basedpyright`; `just lint correct` also fixes and formats | | `just build` | the wheel and the sdist, in `dist/` (needs [`uv`](https://docs.astral.sh/uv/)) | | `just release X.Y.Z` | makes the release tag (see [Releases](#releases)) | @@ -32,7 +32,7 @@ Each version of `sclang` from 3.14 must parse the schelp output with no error an 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. +GitHub Actions (`.github/workflows/tests.yml`) runs the checks of `ruff` and `basedpyright`. It 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 diff --git a/just/project/lint.sh b/just/project/lint.sh new file mode 100644 index 0000000..1fafb1d --- /dev/null +++ b/just/project/lint.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# ruff (check and format) and basedpyright, with the tools of .venv if it +# exists. The argument `correct` also fixes and formats the code. `just lint` +# runs actionlint before this script. +set -euo pipefail +cd "$(dirname "$0")/../.." +python=.venv/bin/python +[ -x "$python" ] || python=python3 +if [ "${1:-check}" = correct ]; then + "$python" -m ruff check --fix . + "$python" -m ruff format . +fi +"$python" -m ruff check . +"$python" -m ruff format --check . +"$python" -m basedpyright --pythonpath "$("$python" -c 'import sys; print(sys.executable)')" diff --git a/md2misc/backends/base.py b/md2misc/backends/base.py index 22eb230..d6e9762 100644 --- a/md2misc/backends/base.py +++ b/md2misc/backends/base.py @@ -16,7 +16,7 @@ class Backend: # the name of the format, for messages name = "this" - def unsupported(self, construct: str, line: int = None): + def unsupported(self, construct: str, line: int | None = None): """ stop the conversion: the format has no way to write `construct`. `line` is the line of the construct in the Markdown text, if it is known. @@ -46,6 +46,30 @@ def unsupported(self, construct: str, line: int = None): # md2tex keeps them in the code strip_quote_marks_in_code = False + # whether the format has methods sections (`MDMethods`). a backend that sets it also sets the next three + # attributes and `method_heading_regex()` + supports_methods = False + + # the methods sections: the text of a level 2 heading, in lower case, to the mark of the method names + methods_sections: dict = {} + + # the text that starts the paragraph of a return value + returns_mark = "" + + # a heading that starts the discussion of a method + discussion_heading_regex = "" + + # whether the format has tables outside the methods sections (`MDTable`). a backend that sets it also + # overrides `table()` + supports_tables = False + + @staticmethod + def method_heading_regex(mark: str) -> str: + """ + the form of a method heading in a methods section. `mark` is the mark of the section. + """ + raise NotImplementedError + def check_source(self, markdown: str): """ look at the Markdown text before it is converted. a backend can stop the conversion with an @@ -149,13 +173,19 @@ def link(self, url: str, text: str) -> str: """ self.unsupported("link") + def table(self, header: list, rows: list) -> str: + """ + write a table. `header` is the cells of the header row, `rows` the cells of each body row. + """ + self.unsupported("table") + def insertion(self, name: str) -> str: """ write what the caller gave for the insertion point `name`. only called if `supports_insertions` is true. """ raise NotImplementedError - def internal_link(self, target: str, text: str): + def internal_link(self, target: str, text: str) -> str | None: """ write a link to a target that is not an external URL (a page or a file, for example). `target` and `text` are escaped. return `None` to leave the link as it is in the text. @@ -168,7 +198,7 @@ def footnote(self, text: str) -> str: """ self.unsupported("footnote") - def citation(self, key: str, locator: str = None, is_range: bool = False, omit_author: bool = False) -> str: + def citation(self, key: str, locator: str | None = None, is_range: bool = False, omit_author: bool = False) -> str: """ write a citation of one source. `locator` is a page number, or a range of pages if `is_range` is true. `omit_author` is true if the author must not be named. @@ -200,7 +230,9 @@ def inline_code(self, code: str) -> str: """ raise NotImplementedError - def code_block(self, code: str, language: str = None, title: str = None, highlight_lines: str = None) -> str: + def code_block( + self, code: str, language: str | None = None, title: str | None = None, highlight_lines: str | None = None + ) -> str: """ write a block of code. `code` is not escaped. `language` is the language from the info string of the code block, if any. `title` is the title, if any. `highlight_lines` is the lines to diff --git a/md2misc/backends/schelp.py b/md2misc/backends/schelp.py index 1eda861..f91af22 100644 --- a/md2misc/backends/schelp.py +++ b/md2misc/backends/schelp.py @@ -1,9 +1,9 @@ import re from itertools import chain -from .base import Backend from .. import citations, syntax, tables from ..errors_warnings import DocumentError, UnsupportedConstruct +from .base import Backend class SchelpBackend(Backend): @@ -80,7 +80,7 @@ def method_heading_regex(mark: str) -> str: header_keys = ["class", "title", "summary", "related", "categories"] list_keys = ["related", "categories"] - def __init__(self, insertions: dict = None, bibliography=None): + def __init__(self, insertions: dict | None = None, bibliography=None): self.bibliography = bibliography # the path of the bibliography file for the citations, or None self.stash = {} self.insertions = dict(insertions or {}) @@ -91,7 +91,7 @@ def __init__(self, insertions: dict = None, bibliography=None): # ------------------------------------------------------ the header @classmethod - def _header_value(cls, key: str, value, line: int = None): + def _header_value(cls, key: str, value, line: int | None = None): """ check the value of a header key and give it its form: a list for `related` and `categories`, else a string. @@ -244,7 +244,7 @@ def _check_heading_source(self, text: str, line: int): ): self.unsupported("link, footnote or citation in a heading", line) - def _check_citation(self, citation: str, line: int = None): + def _check_citation(self, citation: str, line: int | None = 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`. @@ -1014,7 +1014,9 @@ def inline_code(self, code: str) -> str: # in the inline form of a tag, `::` in the text needs a backslash return self._stash(self._inline("code", code.replace("::", "\\::"))) - def code_block(self, code: str, language: str = None, title: str = None, highlight_lines: str = None) -> str: + def code_block( + self, code: str, language: str | None = None, title: str | None = None, highlight_lines: str | None = None + ) -> str: if title: self.unsupported("code block title") if highlight_lines: diff --git a/md2misc/backends/tex.py b/md2misc/backends/tex.py index 465c6de..ac4be59 100644 --- a/md2misc/backends/tex.py +++ b/md2misc/backends/tex.py @@ -1,9 +1,9 @@ import re -from .base import Backend -from .minted import languages from ..errors_warnings import Warnings from ..helpers import get_matching_brackets +from .base import Backend +from .minted import languages class TeXBackend(Backend): @@ -161,7 +161,7 @@ def link(self, url: str, text: str) -> str: def footnote(self, text: str) -> str: return "\\footnote{" + text + "}" - def citation(self, key: str, locator: str = None, is_range: bool = False, omit_author: bool = False) -> str: + def citation(self, key: str, locator: str | None = None, is_range: bool = False, omit_author: bool = False) -> str: tex_locator = "" if locator: tex_locator = f"[pp. {locator}]" if is_range else f"[p. {locator}]" @@ -180,7 +180,9 @@ def display_math(self, expression: str) -> str: def inline_code(self, code: str) -> str: return "\\mintinline{" + self.minted_language + "}{" + code + "}" - def code_block(self, code: str, language: str = None, title: str = None, highlight_lines: str = None) -> str: + def code_block( + self, code: str, language: str | None = None, title: str | None = None, highlight_lines: str | None = None + ) -> str: env = r""" \begin{listing}[H] \begin{minted}{@@LANGTOKEN@@} diff --git a/md2misc/converters.py b/md2misc/converters.py index 13aaaee..66275c1 100644 --- a/md2misc/converters.py +++ b/md2misc/converters.py @@ -1,10 +1,10 @@ import re -from itertools import chain +from typing import cast from . import syntax, tables -from .helpers import process_list_indentation -from .errors_warnings import Warnings from .backends import Backend +from .errors_warnings import Warnings +from .helpers import process_list_indentation # --------------------------------------------------------------- # regex based conversion from markdown to other formats; @@ -81,7 +81,7 @@ def convert(string: str, backend: Backend): # remaining levels. a later pass removes the blank lines that an earlier pass left for group in range(1, backend.heading_groups + 1): - def write_heading(m): + def write_heading(m, group=group): level = int(m[1]) if level == group or (group == backend.heading_groups and level > group): return backend.heading(level, m[2]) @@ -221,7 +221,7 @@ def definition_l(string: str, backend: Backend): lists.append(current_list) for ls in lists: - ls_block = "".join([l[0] for l in ls]) + ls_block = "".join([item[0] for item in ls]) entries = [] # list of (term, definition) for item in ls: @@ -287,7 +287,9 @@ def block_code(string: str, backend: Backend): string = string.replace(code, "@@BLOCKCODETOKEN@@") # to reinject code to string later # extract info string - info_string = re.search(r"```([^\n]*)$", code, flags=re.M)[0].replace("```", "").strip() # ugly but works + fence = re.search(r"```([^\n]*)$", code, flags=re.M) + assert fence is not None # a code block starts with a fence line + info_string = fence[0].replace("```", "").strip() # ugly but works # extract code body code_body = re.sub(r"```.*?\n((.|\n)+?)```", r"\1", code, flags=re.M) @@ -297,7 +299,7 @@ def block_code(string: str, backend: Backend): prefix = source[source.rfind("\n", 0, m.start()) + 1 : m.start()] if re.fullmatch(r"[ \t]*(>[ \t]*)+", prefix): depth = prefix.count(">") - code_body = re.sub(r"^[ \t]*(?:>[ \t]?){1,%d}" % depth, "", code_body, flags=re.M) + code_body = re.sub(rf"^[ \t]*(?:>[ \t]?){{1,{depth}}}", "", code_body, flags=re.M) # assume language is the first word in the info string # cf. https://spec.commonmark.org/0.31.2/#fenced-code-blocks @@ -353,29 +355,30 @@ def footnote(string: str, backend: Backend): caret = re.escape(backend.escape("^")) fnote_pointers = re.finditer(r"\[" + caret + r"\d+\](?![ \t]*:)", string, flags=re.M) for match in fnote_pointers: - try: - pointer = match[0] # extract the footnote pointer (the pointer to the actual footnote) - fnote_num = re.search(r"\d+", pointer)[0] # extract the footnote nΒ° - fnote_text = re.search( - r"^(\[" + caret + fnote_num + r"\]:) *(.+\n?)", string, flags=re.M - ) # match the proper footnote (with the good fnote_num) - # remove the pointer + normalize space - note = re.sub(r"\s+", " ", fnote_text[0].replace(fnote_text[1], "")).strip() - - if not re.search(r"^\s*$", note): # if the note isn't empty; else, delete it - note = backend.footnote(note) - string = string.replace(fnote_text[0], "") # delete the markdown footnote - string = string.replace(pointer, note) # add the footnote to string - else: - # delete the footnote body and pointers - string = string.replace(pointer, "") - string = string.replace(fnote_text[0], "") - - except TypeError: + pointer = match[0] # extract the footnote pointer (the pointer to the actual footnote) + number = re.search(r"\d+", pointer) + assert number is not None # a pointer has digits + fnote_num = number[0] # extract the footnote nΒ° + fnote_text = re.search( + r"^(\[" + caret + fnote_num + r"\]:) *(.+\n?)", string, flags=re.M + ) # match the proper footnote (with the good fnote_num) + if fnote_text is None: # a footnote pointer may point to nothing; conversely, a footnote # may to have a ref in the body. in that case, pass now and delete every loose # footnote part right after - pass + continue + # remove the pointer + normalize space + note = re.sub(r"\s+", " ", fnote_text[0].replace(fnote_text[1], "")).strip() + + if not re.search(r"^\s*$", note): # if the note isn't empty; else, delete it + note = backend.footnote(note) + string = string.replace(fnote_text[0], "") # delete the markdown footnote + string = string.replace(pointer, note) # add the footnote to string + else: + # delete the footnote body and pointers + string = string.replace(pointer, "") + string = string.replace(fnote_text[0], "") + # delete all loose footnote strings string = re.sub(r"\[" + caret + r"\d+\](?![ \t]*:)", "", string, flags=re.M) string = re.sub(r"(\[" + caret + r"\d+\]:)(.+\n?)*", "", string, flags=re.M) @@ -457,7 +460,11 @@ def citation(string: str, backend: Backend): citation_text = backend.citations(keys) else: # only one citation, so we split into citation key and locator - ref_components = re.match(r"(-?@[^, ]+)(, (?:p\. )?(\d+\b(?!-))|, (?:pp\. )?(\d+-\d+))?", ref_string[1]) + # a citation of another form, such as `[@ doe]`, has no match and stops with a TypeError + ref_components = cast( + "re.Match[str]", + re.match(r"(-?@[^, ]+)(, (?:p\. )?(\d+\b(?!-))|, (?:pp\. )?(\d+-\d+))?", ref_string[1]), + ) citation_key = ref_components[1] locator = ref_components[3] or ref_components[4] omit_author = citation_key.startswith("-") @@ -827,7 +834,8 @@ def convert(string: str, backend: Backend): return string def write(match): - header, rows = None, [] + header: list = [] + rows = [] for line in match[1].split("\n"): if line.startswith(MDTable.header): header = line[len(MDTable.header) :].split(MDTable.separator) diff --git a/md2misc/core.py b/md2misc/core.py index 35c0b9f..e97e6be 100644 --- a/md2misc/core.py +++ b/md2misc/core.py @@ -1,22 +1,22 @@ import importlib.resources from .backends import SchelpBackend, TeXBackend -from .errors_warnings import DocumentError from .converters import ( - MDSimple, - MDQuote, - MDList, - MDCode, MDCleaner, - MDReference, - MDHeader, + MDCode, MDFrontmatter, + MDHeader, MDInsertion, - MDMedia, + MDList, MDMath, + MDMedia, MDMethods, + MDQuote, + MDReference, + MDSimple, MDTable, ) +from .errors_warnings import DocumentError def default_template() -> str: diff --git a/md2misc/errors_warnings.py b/md2misc/errors_warnings.py index fbc8eee..e42b60f 100644 --- a/md2misc/errors_warnings.py +++ b/md2misc/errors_warnings.py @@ -1,6 +1,5 @@ import warnings - # ------------------------------------------------------- # custom error and warnings classes to display custom # messages @@ -33,7 +32,7 @@ class UnsupportedConstruct(Md2miscError): known. `describe(source)` gives the message with the name of the Markdown file. """ - def __init__(self, backend: str, construct: str, line: int = None): + def __init__(self, backend: str, construct: str, line: int | None = None): """ :param backend: the name of the output format :param construct: the name of the Markdown construct, for example `block quote` @@ -44,7 +43,7 @@ def __init__(self, backend: str, construct: str, line: int = None): self.line = line super().__init__(self.describe()) - def describe(self, source: str = None) -> str: + def describe(self, source: str | None = None) -> str: """ the message. `source` is the name of the Markdown file, if known. """ diff --git a/md2misc/helpers.py b/md2misc/helpers.py index a9368aa..330e0fd 100644 --- a/md2misc/helpers.py +++ b/md2misc/helpers.py @@ -42,9 +42,9 @@ def process_list_indentation(lstext): ] """ lsitems = [] # list of lists : [item content, indentation level] - firstindent = len(re.search(r"^\s*", lstext)[0]) # base indentation level + firstindent = len(lstext) - len(lstext.lstrip()) # base indentation level for item in re.split(r"\n", lstext): - indent = len(re.search(r"^\s*", item)[0]) - firstindent + indent = len(item) - len(item.lstrip()) - firstindent if indent < 0: raise IndentationException(key="firstindent", lstext=lstext) # raise an error, print error msg, exit else: @@ -59,7 +59,7 @@ def process_list_indentation(lstext): # - check that all levels have a common multiplier # - replace absolute number of spaces (li[1]) by indentation level (li[1] / mult) # - if an item jumps indentation level (e.g., goes from level 1 to level3), correct it - if len(set([li[1] for li in lsitems])) > 1: # if there are different indentation levels + if len({li[1] for li in lsitems}) > 1: # if there are different indentation levels mult = next((li[1] for li in lsitems if li[1] != 0), 0) # the first indented item is the multiplier for li in lsitems: diff --git a/pyrightconfig.json b/pyrightconfig.json new file mode 100644 index 0000000..52c4b6b --- /dev/null +++ b/pyrightconfig.json @@ -0,0 +1,4 @@ +{ + "typeCheckingMode": "standard", + "failOnWarnings": false +} diff --git a/ruff.toml b/ruff.toml index 5470aa8..2ee0673 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,5 +1,7 @@ line-length = 120 include = ["*.py", "*.pyi"] +# the folders of md2misc and of the helper modules of the tests, for the order of the imports +src = [".", "tests"] force-exclude = true preview = false unsafe-fixes = false diff --git a/tests/battery.py b/tests/battery.py index cde1612..39c8190 100644 --- a/tests/battery.py +++ b/tests/battery.py @@ -45,11 +45,11 @@ REPO = HERE.parent # The arguments that the book build gives to convert(). -CONVERT_ARGS = dict( - document_class="article", - minted_language="./sc_lexer.py:SuperColliderLexer", - override_language=True, -) +CONVERT_ARGS = { + "document_class": "article", + "minted_language": "./sc_lexer.py:SuperColliderLexer", + "override_language": True, +} # The private markers that the book build puts into the Markdown. MARKER_RE = re.compile( @@ -142,12 +142,14 @@ def load_preprocessor(workdir: Path): sys.path.insert(0, str(BUILD_REPO)) # parse_docs imports md2tex at module level, but the preprocessing never # calls it. A stand-in module is enough. - sys.modules.setdefault("md2tex", types.SimpleNamespace(convert=None)) + stand_in = types.ModuleType("md2tex") + setattr(stand_in, "convert", None) + sys.modules.setdefault("md2tex", stand_in) parse_docs = importlib.import_module("parse_docs") (workdir / "tex/diagrams").mkdir(parents=True) os.chdir(workdir) - parse_docs.MERMAID_DIAGRAM_DIR = "./tex/diagrams/" + setattr(parse_docs, "MERMAID_DIAGRAM_DIR", "./tex/diagrams/") parse_docs.subprocess.run = lambda *a, **k: None # no headless browser return parse_docs.preprocess_mkdocs_markdown diff --git a/tests/schelp_fixtures.py b/tests/schelp_fixtures.py index 6c4de6d..b47abf2 100644 --- a/tests/schelp_fixtures.py +++ b/tests/schelp_fixtures.py @@ -94,7 +94,7 @@ def body_of(html: str) -> str: return body.strip() + "\n" -def find_sclang(path: str = None): +def find_sclang(path: str | None = None): """The path of sclang, or `None`.""" return path or os.environ.get("SCLANG") or shutil.which("sclang") @@ -114,7 +114,7 @@ def fixture_version() -> str: return VERSION_FILE.read_text().strip() -def render_texts(sclang: str, texts: dict, timeout: int = 180, copied: list = None) -> dict: +def render_texts(sclang: str, texts: dict, timeout: int = 180, copied: list | None = 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 From f7f3ee43362df3d466ec96f4b77eed0aa1f22fea Mon Sep 17 00:00:00 2001 From: Anders Eskildsen <22001464+aeskildsen@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:12:18 +0100 Subject: [PATCH 4/5] ci: limit the token of the test workflow to read access --- .github/workflows/tests.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9906fce..1c8fb4e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -5,6 +5,9 @@ on: branches: [main] pull_request: +permissions: + contents: read + jobs: # ruff and basedpyright, with the Python that the package needs at least. lint: From 3205ce73598eade05a99a1b2f87cd17ce9b457ca Mon Sep 17 00:00:00 2001 From: Anders Eskildsen <22001464+aeskildsen@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:27:32 +0100 Subject: [PATCH 5/5] docs: follow the repository standard; add CHANGELOG.md - Add CHANGELOG.md with a section for each version tag. - `just release` checks the branch, the version and the changelog section. - CLAUDE.md becomes AGENTS.md, with the rules for agents only. - docs/development.md becomes DEVELOPING.md. The design notes are in docs/design.md. - README.md has the standard sections. --- AGENTS.md | 12 +++++ CHANGELOG.md | 71 ++++++++++++++++++++++++ CLAUDE.md | 22 -------- CONTRIBUTING.md | 3 +- docs/development.md => DEVELOPING.md | 80 +++++++++++++++++++++------- README.md | 19 ++++--- docs/design.md | 37 +++++++++++++ just/project/test.sh | 2 +- justfile | 37 +++++++++++++ 9 files changed, 229 insertions(+), 54 deletions(-) create mode 100644 AGENTS.md create mode 100644 CHANGELOG.md delete mode 100644 CLAUDE.md rename docs/development.md => DEVELOPING.md (56%) create mode 100644 docs/design.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..6c94e7c --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,12 @@ +# AGENTS.md + +Rules for coding agents. [DEVELOPING.md](DEVELOPING.md) has the toolchain, the commands, the tests and the release steps. Read [docs/design.md](docs/design.md) before you change the converters or a backend. + +- Before you finish a change, run `just lint` and `just test`. Report the tests that were skipped. +- `tests/fixtures/*.tex` is the output of md2tex f90f23b. It is the reference. Change a `.tex` file only if the TeX output is meant to change. +- Never run `tests/battery.py build` against changed converter code. +- The TeX fixtures test article-numbered TeX and the heading variants only. After a change in the converters, also compare the output and the errors with the old code on edge cases. +- A Markdown construct without a schelp form goes in three places (see [docs/design.md](docs/design.md#constructs-without-a-schelp-form)). +- After a schelp change, make the fixtures again and read the diff (see [DEVELOPING.md](DEVELOPING.md#fixture-tools)). +- A change in behaviour adds its line under `## [Unreleased]` in [CHANGELOG.md](CHANGELOG.md). +- Do not put details of your computer in committed files, commit messages or pull requests: no home paths, host names or user names. Use placeholders such as ``. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..0cec8c0 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,71 @@ +# Changelog + +All important changes to md2misc are in this file. The format is from [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). md2misc uses [Semantic Versioning](https://semver.org/). Before version 1.0, a change to the minor version (0.1 to 0.2) can change the arguments or the output. A change to the patch version (0.1.0 to 0.1.1) only fixes problems. + +## [Unreleased] + +### Changed + +- md2misc needs Python 3.12 or later. +- The build backend is `uv_build` in place of setuptools. A build from source needs it. + +## [0.4.0] - 2026-11-18 + +### Added + +- schelp: citations. With the new `bibliography` argument of `convert_schelp`, each citation becomes a footnote that the program `pandoc` writes. +- schelp: pipe tables outside the methods sections. +- schelp: an image alone in a paragraph. +- schelp: the `## Instance methods` section, and a `#### Discussion` heading in a method. +- schelp: block quotes that are not alerts, as text in italics in quotation marks. +- schelp: footnotes with more than one line and paragraph. + +### Fixed + +- schelp: an inline tag or a footnote directly after a letter gave markup that SCDoc cannot read. +- The wheel and the sdist have the `NOTICE` file, and the sdist has the complete test setup. + +### Changed + +- The licence is stated as GPL-3.0-only. + +## [0.3.0] - 2026-11-17 + +### Added + +- schelp: the `## Class methods` section, with method headings, argument tables and return values. + +## [0.2.0] - 2026-11-17 + +### Added + +- `default_template`, the error classes (`Md2miscError` and its subclasses) and the warning class `Md2miscWarning` are in the `md2misc` package. + +### Changed + +- All errors are subclasses of `Md2miscError`, and no longer exceptions of `click`. +- Warnings go through the `warnings` module of Python. +- `convert` stops with `DocumentError` if the document class is not `article` or `book`. + +### Removed + +- The `md2misc` command and the dependency on `click`. md2misc is a library only. + +## [0.1.0] - 2026-11-17 + +The first release of md2misc, which is derived from [md2tex](https://github.com/paulhectork/md2tex). + +### Added + +- A backend for SuperCollider help files (schelp), with the function `convert_schelp`. +- The `md2misc` command, with a subcommand for each output format. + +### Changed + +- The package and the command have the name md2misc. The function `convert` writes the same TeX as md2tex, with one difference: a `#` followed at once by an escaped character is a heading. + +[Unreleased]: https://github.com/aeskildsen/md2misc/compare/v0.4.0...HEAD +[0.4.0]: https://github.com/aeskildsen/md2misc/compare/v0.3.0...v0.4.0 +[0.3.0]: https://github.com/aeskildsen/md2misc/compare/v0.2.0...v0.3.0 +[0.2.0]: https://github.com/aeskildsen/md2misc/compare/v0.1.0...v0.2.0 +[0.1.0]: https://github.com/aeskildsen/md2misc/releases/tag/v0.1.0 diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 2b1491b..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,22 +0,0 @@ -# md2misc - -Markdown to TeX (the same output as md2tex) and to SuperCollider help (schelp). README.md has the usage. - -## Tests - -- There is no Nix tooling: the package is `pyproject.toml` only. The tests run in `.venv`, made in the `dev` distrobox with the Python of Ubuntu (in the container, `python3` on `PATH` is the Nix one of the host): `distrobox enter dev -- fish -lc 'cd ; and uv venv --python /usr/bin/python3 .venv; and uv pip install --python .venv/bin/python -e ".[test]"'`. Then `distrobox enter dev -- fish -lc 'cd ; and .venv/bin/python -m pytest'`. `` is the folder of this repository. -- Before you finish a change, run `just lint` in the same way as the tests (`just lint correct` also formats). -- 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. -- 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 ; 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 - -- `converters.py` finds the Markdown. `backends/` writes the output. There is no TeX or schelp string in `converters.py`. -- `syntax.py` holds the regular expressions of the Markdown constructs. The converters and `SchelpBackend.check_source()` use them, so that both find the same constructs. A backend selects the strict CommonMark/Pandoc form of headings and inline math, and whether quote marks are removed from code in a block quote; `TeXBackend` keeps the md2tex forms. -- Kept from md2tex, so that the TeX output stays the same: `TeXBackend.remove_quote_marks()` turns every `>` into a space, so a `
` tag is never found. One known difference: a `#` followed at once by an escaped character (`#_x`) is a heading now (md2tex: text). -- A Markdown construct without a schelp form goes in three places: the writer in `SchelpBackend`, `SchelpBackend.check_source()` (it gives the line, which the converters cannot) and `tests/schelp_cases.py` (`UNSUPPORTED`). If the converters take the construct for text (tables, `*` lists, HTML), it goes in `check_source()` and `SOURCE_ONLY` only. -- Tables: `tables.py` has the GFM rules for rows (cells, delimiter row, end of the table); `check_source()` and `MDMethods` both use it. The only table that a backend writes is the argument table of the schelp class methods section. Where renderers disagree (pipes in code spans, `\\|`, a line without a pipe after a table), the check stops. To check an expected value against GitHub's parser: `nix shell nixpkgs#cmark-gfm -c cmark-gfm -e table`. -- SCDoc (3.14.1): in prose, `::`, `##` and `||` need a backslash. In a header line only `::` does, and `##` or `||` cannot be written. Modal tags (`strong::`, `emphasis::`, inline `code::`, `link::`) cannot hold other tags. The name of a section is plain text. In the inline form of a tag, a `:` or `\` at the end of the text joins the end-tag: a space before `::` keeps them apart (`\::` there is a syntax error). A link splits at each `#` (page, anchor, label), and a `#` in the label cannot be escaped. A backslash before other characters, `$` too, is text. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b2e5433..a4c41e9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,7 +10,8 @@ Contributions are welcome. Read the [issue and pull request rules](#issue-and-pu ## This repository -- [docs/development.md](docs/development.md) tells you how to set up the environment, run the tests and make a release. +- [DEVELOPING.md](DEVELOPING.md) tells you how to set up the environment, run the tests and make a release. +- A pull request that changes behaviour adds its line under `## [Unreleased]` in [CHANGELOG.md](CHANGELOG.md). - The TeX fixtures in `tests/fixtures` are the output of `md2tex` and the reference for the TeX backend. Change them only if the TeX output is meant to change. ## Issue and pull request rules diff --git a/docs/development.md b/DEVELOPING.md similarity index 56% rename from docs/development.md rename to DEVELOPING.md index 0499e63..2bb596a 100644 --- a/docs/development.md +++ b/DEVELOPING.md @@ -1,29 +1,59 @@ -# Development +# Developing md2misc -## Recipes +[docs/design.md](docs/design.md) describes the structure of the code. Changes to `main` go through a pull request. + +## Toolchain + +md2misc uses the tools of Python. It has no Nix setup. + +| Tool | Version | For | +|---|---|---| +| Python | 3.12 or later | the package and the tests | +| [`just`](https://just.systems) | 1.23.0 or later | the recipes | +| [`actionlint`](https://github.com/rhysd/actionlint) | | `just lint` | +| [`uv`](https://docs.astral.sh/uv/) | | `just build`, and the virtual environment if you want | +| SuperCollider (`sclang`) | 3.14 or later | the SCDoc tests (optional) | +| [`pandoc`](https://pandoc.org) | | the citation tests (optional) | + +Make a virtual environment in `.venv`, in the repository folder. The recipes use it if it exists, else the `python3` on `PATH`. With `venv`: + +```bash +python3 -m venv .venv +.venv/bin/python -m pip install -e ".[test]" +``` -The [`just`](https://just.systems) recipes run the common tasks. Activate the virtual environment, or keep it in `.venv`. +Or with `uv`: + +```bash +uv venv .venv +uv pip install --python .venv/bin/python -e ".[test]" +``` + +The `test` extra of `pyproject.toml` has pytest, `ruff` and `basedpyright`. + +## Recipes | Recipe | What it runs | |---|---| +| `just setup` | nothing: make the virtual environment as shown above | | `just check` | `just test` | | `just test` | all tests (`pytest`) | -| `just lint` | `actionlint`, `ruff check`, `ruff format --check` and `basedpyright`; `just lint correct` also fixes and formats | -| `just build` | the wheel and the sdist, in `dist/` (needs [`uv`](https://docs.astral.sh/uv/)) | -| `just release X.Y.Z` | makes the release tag (see [Releases](#releases)) | +| `just lint` | `actionlint`, `ruff check`, `ruff format --check` and `basedpyright` | +| `just lint correct` | the same, after `ruff` fixes and formats the code | +| `just build` | `uv build`: the wheel and the sdist, in `dist/` | +| `just release X.Y.Z` | checks, then the release tag (see [Releases](#releases)) | -Changes to `main` go through a pull request. +## Build + +The build backend is `uv_build`; its settings and its version range are in `pyproject.toml`. The sdist has the complete test setup: the tests, their helper modules and the fixtures. ## Tests -The tests use pytest. In a virtual environment, from a checkout of this repository: +The tests use pytest. ```bash -python3 -m venv .venv -. .venv/bin/activate -pip install -e ".[test]" -python3 -m pytest # all tests -python3 -m pytest -k schelp # the schelp tests +just test # all tests +.venv/bin/python -m pytest -k schelp # the schelp tests ``` The tests of the SCDoc output run headless `sclang` (SuperCollider). They are skipped if `sclang` is not on `PATH` or in the `SCLANG` environment variable, so a contributor to another backend does not need SuperCollider. With `MD2MISC_REQUIRE_SCLANG=1`, a missing `sclang` is an error and not a skip. @@ -32,9 +62,7 @@ Each version of `sclang` from 3.14 must parse the schelp output with no error an 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 the checks of `ruff` and `basedpyright`. It 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 +### Test files - `tests/test_tex_battery.py`: the TeX output is the same as the output of `md2tex`, for the fixtures in `tests/fixtures` (pages of a book and the `md2tex` README, with a coverage table in `tests/COVERAGE.md`). - `tests/test_schelp_golden.py`: the schelp output is the same as the `.schelp` files in `tests/schelp`. @@ -48,16 +76,28 @@ GitHub Actions (`.github/workflows/tests.yml`) runs the checks of `ruff` and `ba - `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 +### 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, `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. +## CI + +`.github/workflows/tests.yml` runs on each pull request and on each push to `main`: + +| Job | What it runs | +|---|---| +| `lint` | `just/project/lint.sh` (`ruff` and `basedpyright`) with Python 3.12 | +| `python` | all tests against the installed package, with Python 3.12 and 3.14 and the `pandoc` of Ubuntu | +| `scdoc` | the schelp tests in a `debian:forky` container, with its SuperCollider and `pandoc`; no test is skipped for a missing program | + +Ubuntu 24.04 has SuperCollider 3.13, which cannot read the schelp output. The CodeQL checks come from the default setup of GitHub code scanning. + ## Releases A release is an annotated git tag `vX.Y.Z` on `main`. Other projects pin md2misc to a tag (for example as a git submodule), so do not move or delete a tag after it is pushed. -1. Set `version` in `pyproject.toml` to the new version, in the pull request of the last change of the release or in a pull request of its own. -2. Make sure that GitHub Actions passes on that commit of `main`. GitHub Actions runs the SCDoc tests too, so SuperCollider is not necessary on your computer. -3. Check out that commit and tag it: `just release X.Y.Z`. The tag and the version in `pyproject.toml` must agree. +1. In a pull request, set `version` in `pyproject.toml` to the new version. In [CHANGELOG.md](CHANGELOG.md), move the lines under `## [Unreleased]` to a new section `## [X.Y.Z] - YYYY-MM-DD`, and update the links at the end of the file. +2. Merge the pull request. Make sure that GitHub Actions passes on that commit of `main`. GitHub Actions runs the SCDoc tests too, so SuperCollider is not necessary on your computer. +3. Check out `main` at that commit and run `just release X.Y.Z`. It stops if the working tree is not clean, the branch is not `main`, the version in `pyproject.toml` is different, `CHANGELOG.md` has no section for the version, or the tag exists. 4. Push the tag: `git push origin vX.Y.Z`. A GitHub release for the tag is optional. diff --git a/README.md b/README.md index 0b3cee3..50c86bf 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # md2misc -`md2misc` is a Python library that converts Markdown to other text formats. It finds the elements of Markdown with regular expressions and writes them in the target syntax. It has only been tested with latin script. +`md2misc` is a Python library that converts Markdown to other text formats. It finds the elements of Markdown with regular expressions and writes them in the target syntax. It is for projects that write their documentation in Markdown and need TeX or SuperCollider help files from it. It has only been tested with latin script. Each output format is a *backend*: @@ -9,7 +9,7 @@ Each output format is a *backend*: | TeX | `convert` | [docs/tex.md](docs/tex.md) | | SuperCollider help (schelp) | `convert_schelp` | [docs/schelp.md](docs/schelp.md) | -## Installation +## Install `md2misc` needs Python 3.12 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)). @@ -17,7 +17,7 @@ Each output format is a *backend*: pip install git+https://github.com/aeskildsen/md2misc ``` -## Usage +## Use ```python from md2misc import convert, convert_schelp @@ -53,18 +53,17 @@ All errors are subclasses of `md2misc.Md2miscError`: Warnings have the category `md2misc.Md2miscWarning`. Use the `warnings` module to filter them or to make them errors. -Version 0.2.0 removed the `md2misc` command and the dependency on `click`. +## Origin + +`md2misc` is derived from [`md2tex`](https://github.com/paulhectork/md2tex) by Paul Kervegan. The full history of `md2tex`, with the commits of both authors, is part of the git history of this repository. The TeX output is meant to stay identical to the output of `md2tex`. See `NOTICE`. ## Documentation - [docs/tex.md](docs/tex.md): the TeX backend, the supported Markdown and the rules for lists - [docs/schelp.md](docs/schelp.md): the schelp backend, the header, the insertion points and the constructs that stop the conversion -- [docs/development.md](docs/development.md): how to run the tests - -## Origin - -`md2misc` is derived from [`md2tex`](https://github.com/paulhectork/md2tex) by Paul Kervegan. The full history of `md2tex`, with the commits of both authors, is part of the git history of this repository. The TeX output is meant to stay identical to the output of `md2tex`. See `NOTICE`. +- [CHANGELOG.md](CHANGELOG.md): the changes in each version +- [DEVELOPING.md](DEVELOPING.md): for contributors -## License and credits +## Licence Released under the GNU General Public License version 3 only (GPL-3.0-only). `md2tex` was developed by Paul Kervegan in August 2022. Later additions to `md2tex` were made by Anders Eskildsen, and `md2misc` continues from there. See `NOTICE`. diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..877de3c --- /dev/null +++ b/docs/design.md @@ -0,0 +1,37 @@ +# Design + +## Modules + +- `converters.py` finds the Markdown. `backends/` writes the output. A new TeX or schelp string goes in a backend, not in `converters.py`. One exception exists: `MDMethods.convert()` writes the method tags of schelp. +- `syntax.py` holds the regular expressions of the Markdown constructs. The converters and `SchelpBackend.check_source()` use them, so that both find the same constructs. A backend selects the strict CommonMark/Pandoc form of headings and inline math, and whether quote marks are removed from code in a block quote. `TeXBackend` keeps the md2tex forms. + +## Behaviour kept from md2tex + +The TeX output stays the same as the output of md2tex. Thus `TeXBackend.remove_quote_marks()` turns every `>` into a space, so a `
` tag is never found. One known difference exists: a `#` followed at once by an escaped character (`#_x`) is a heading in md2misc, and text in md2tex. + +## Constructs without a schelp form + +A Markdown construct without a schelp form goes in three places: + +1. the writer in `SchelpBackend` +2. `SchelpBackend.check_source()`, which gives the line (the converters cannot) +3. `tests/schelp_cases.py` (`UNSUPPORTED`) + +If the converters take the construct for text (for example `*` lists and HTML), it goes in `check_source()` and `SOURCE_ONLY` only. + +## Tables + +`tables.py` has the GFM rules for rows: the cells, the delimiter row and the end of the table. `SchelpBackend.check_source()`, `MDMethods` and `MDTable` use it. Only the schelp backend writes tables. Where Markdown renderers do not agree (pipes in code spans, `\\|`, a line without a pipe after a table), the check stops the conversion. + +To compare an expected value with the parser of GitHub, run `cmark-gfm -e table`. + +## SCDoc markup + +These facts are for SCDoc 3.14.1. + +- In prose, `::`, `##` and `||` need a backslash. In a header line only `::` does, and `##` or `||` cannot be written. +- Modal tags (`strong::`, `emphasis::`, inline `code::`, `link::`) cannot hold other tags. +- The name of a section is plain text. +- In the inline form of a tag, a `:` or `\` at the end of the text joins the end-tag. A space before `::` keeps them apart (`\::` there is a syntax error). +- A link splits at each `#` (page, anchor, label), and a `#` in the label cannot be escaped. +- A backslash before other characters, `$` too, is text. diff --git a/just/project/test.sh b/just/project/test.sh index 90c629d..2674e47 100644 --- a/just/project/test.sh +++ b/just/project/test.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # All tests, with the Python of .venv if it exists. The SCDoc tests and the -# citation tests are skipped without sclang and pandoc (see docs/development.md). +# citation tests are skipped without sclang and pandoc (see DEVELOPING.md). set -euo pipefail cd "$(dirname "$0")/../.." python=.venv/bin/python diff --git a/justfile b/justfile index 010cfd0..9058957 100644 --- a/justfile +++ b/justfile @@ -1,4 +1,8 @@ # Requires just 1.23.0 or later. + +# The recipe `release` below replaces the recipe from just/tailor.just. +set allow-duplicate-recipes + import 'just/loader.just' # List available recipes @@ -7,3 +11,36 @@ default: # Fast check: all tests (they run in seconds) check: test + +# Create a local release tag with just release x.y.z +release $VERSION: + #!/usr/bin/env bash + set -euo pipefail + + fail() { echo "Error: $*" >&2; exit 1; } + + [[ "${VERSION}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] \ + || fail "VERSION must be in format x.y.z (e.g., 0.1.0)" + + # The tag must match the source files, so the checkout must be clean. + [[ -z "$(git status --porcelain)" ]] || fail "Working directory is not clean" + + branch="$(git branch --show-current)" + [[ "${branch}" == main ]] || fail "Release from main, not from ${branch:-a detached HEAD}" + + # The first line that starts with `version =` is in the [project] table. + version="$(sed -n 's/^version = "\(.*\)"$/\1/p' pyproject.toml | head -n 1)" + [[ "${version}" == "${VERSION}" ]] \ + || fail "pyproject.toml has version ${version}, not ${VERSION}" + + grep -qF "## [${VERSION}] - " CHANGELOG.md \ + || fail "CHANGELOG.md has no section for ${VERSION}" + + ! git show-ref --tags --verify --quiet "refs/tags/v${VERSION}" \ + || fail "Tag v${VERSION} already exists" + + git tag -a "v${VERSION}" -m "md2misc ${VERSION}" + echo "Tag v${VERSION} created on $(git rev-parse --short HEAD)" + echo "" + echo "To publish the release:" + echo " git push origin v${VERSION}"