+++ /dev/null
-comment: off
+++ /dev/null
-[run]
-omit=
- *site-packages*
- tests/*
- markdown/test_tools.py
- markdown/pep562.py
+++ /dev/null
-tests/basic/** linguist-vendored
-tests/extensions/** linguist-vendored
-tests/misc/** linguist-vendored
-tests/options/** linguist-vendored
-tests/php/** linguist-vendored
-tests/pl/** linguist-vendored
-tests/safe_mode/** linguist-vendored
+++ /dev/null
-name: deploy
-
-on:
- push:
- tags:
- - '*'
-
-jobs:
-
- pypi:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v2
- - name: Setup Python
- uses: actions/setup-python@v1
- with:
- python-version: 3.7
- - name: Install dependencies
- run: |
- python -m pip install --upgrade pip setuptools wheel
- - name: Build
- run: |
- python setup.py bdist_wheel sdist --formats gztar
- - name: Publish
- if: success()
- uses: pypa/gh-action-pypi-publish@v1.1.0
- with:
- user: __token__
- password: ${{ secrets.PYPI_PASSWORD }}
-
- ghpages:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v2
- - name: Setup Python
- uses: actions/setup-python@v1
- with:
- python-version: 3.7
- - name: Install dependencies
- run: |
- python -m pip install --upgrade pip setuptools
- python -m pip install -r doc-requirements.txt
- - name: Build
- run: |
- python -m mkdocs build --clean --verbose
- - name: Publish
- if: success()
- uses: peaceiris/actions-gh-pages@v3
- with:
- deploy_key: ${{ secrets.PAGES_DEPLOY_KEY }}
- external_repository: Python-Markdown/Python-Markdown.github.io
- publish_branch: master
- publish_dir: ./site
+++ /dev/null
-name: manual deploy
-
-on:
- workflow_dispatch
-
-jobs:
-
- ghpages:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v2
- - name: Setup Python
- uses: actions/setup-python@v1
- with:
- python-version: 3.7
- - name: Install dependencies
- run: |
- python -m pip install --upgrade pip setuptools
- python -m pip install -r doc-requirements.txt
- - name: Build
- run: |
- python -m mkdocs build --clean --verbose
- - name: Publish
- if: success()
- uses: peaceiris/actions-gh-pages@v3
- with:
- deploy_key: ${{ secrets.PAGES_DEPLOY_KEY }}
- external_repository: Python-Markdown/Python-Markdown.github.io
- publish_branch: master
- publish_dir: ./site
+++ /dev/null
-name: bot
-
-on:
- pull_request:
- branches:
- - '**'
-
-jobs:
- require_changelog:
-
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v2
- - uses: mskelton/changelog-reminder-action@v1
- with:
- # Match any file in the docs/change_log/ dir.
- changelogRegex: "docs/change_log/.*"
- # Only require changelog update if changes were made in markdown/
- include: "markdown/.*"
- message: |
- @${{ github.actor }}, thank you for your contribution. It appears that you have not added a comment to the
- change log describing the changes you have made. Doing so will help to ensure your contribution is accepted.
-
- Please see the [Contributing Guide](https://python-markdown.github.io/contributing/#pull-requests) for details.
-
- markdown-link-check:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v2
- - uses: gaurav-nelson/github-action-markdown-link-check@v1
- with:
- use-quiet-mode: yes
- use-verbose-mode: yes
- check-modified-files-only: yes
- base-branch: master
+++ /dev/null
-# This workflow will install dependencies and run tests/linters with a matrix of tox environments.
-
-name: CI
-
-on:
- push:
- branches:
- - master
- tags:
- - '**'
- pull_request:
- branches:
- - '**'
-
-jobs:
- test:
-
- runs-on: ubuntu-latest
- strategy:
- fail-fast: false
- max-parallel: 4
- matrix:
- tox-env: [py36, py37, py38, py39, py310, pypy3, pygments]
- include:
- - tox-env: py36
- python-version: '3.6'
- - tox-env: py37
- python-version: '3.7'
- - tox-env: py38
- python-version: '3.8'
- - tox-env: py39
- python-version: '3.9'
- - tox-env: py310
- python-version: '3.10'
- - tox-env: pypy3
- python-version: pypy3
- - tox-env: pygments
- python-version: '3.7'
-
- env:
- TOXENV: ${{ matrix.tox-env }}
-
- steps:
- - uses: actions/checkout@v2
- - name: Setup Python ${{ matrix.python-version }}
- uses: actions/setup-python@v2
- with:
- python-version: ${{ matrix.python-version }}
- - name: Install dependencies
- run: |
- sudo apt-get install libtidy-dev
- python -m pip install --upgrade pip tox coverage codecov
- - name: Run tox
- run: python -m tox
- - name: Upload Results
- if: success()
- uses: codecov/codecov-action@v1
- with:
- file: ./coverage.xml
- flags: unittests
- name: ${{ matrix.tox-env }}
- fail_ci_if_error: false
-
- lint:
- runs-on: ubuntu-latest
- strategy:
- fail-fast: false
- max-parallel: 4
- matrix:
- tox-env: [flake8, pep517check, checkspelling]
-
- env:
- TOXENV: ${{ matrix.tox-env }}
-
- steps:
- - uses: actions/checkout@v2
- - name: Setup Python
- uses: actions/setup-python@v2
- with:
- python-version: 3.7
- - name: Install dependencies
- run: |
- python -m pip install --upgrade pip tox
- if [[ "$TOXENV" == 'checkspelling' ]]; then sudo apt-get install aspell aspell-en; fi
- - name: Run tox
- run: python -m tox
+++ /dev/null
-# Byte-compiled / optimized / DLL files
-__pycache__/
-*.py[cod]
-*$py.class
-
-# C extensions
-*.so
-
-# Distribution / packaging
-.Python
-env/
-build/
-develop-eggs/
-dist/
-downloads/
-eggs/
-.eggs/
-lib/
-lib64/
-parts/
-sdist/
-var/
-*.egg-info/
-.installed.cfg
-*.egg
-MANIFEST
-
-# PyInstaller
-# Usually these files are written by a python script from a template
-# before PyInstaller builds the exe, so as to inject date/other infos into it.
-*.manifest
-*.spec
-
-# Installer logs
-pip-log.txt
-pip-delete-this-directory.txt
-
-# Unit test / coverage reports
-htmlcov/
-.tox/
-.coverage
-.coverage.*
-.cache
-nosetests.xml
-coverage.xml
-*,cover
-.hypothesis/
-test-output.html
-
-# Translations
-*.mo
-*.pot
-
-# Scrapy stuff:
-.scrapy
-
-# PyBuilder
-target/
-
-# IPython Notebook
-.ipynb_checkpoints
-
-# pyenv
-.python-version
-
-# virtualenv
-venv/
-ENV/
-
-# MkDocs documentation
-site/
-
-# Mac files
-.DS_Store
+++ /dev/null
-facelessuser
-mitya
-waylan
-Abrahamsen
-Altmayer
-API
-Artem
-aspell
-Babelmark
-backtick
-backticks
-Balogh
-BlockParser
-Blockprocessor
-Blockprocessors
-blockquote
-blockquotes
-boolean
-CamelCase
-Chodarev
-CLI
-CodeHilite
-codehilite
-Cogumbreiro
-convertFile
-CSS
-dedent
-deliminators
-deregister
-Dmitry
-docdata
-ElementTree
-encodings
-extendMarkdown
-Fauske
-formatter
-Fortin
-GitHub
-globals
-Gruber
-GSoC
-hacky
-HeaderId
-HTTPS
-html
-implementers
-InlineProcessor
-Jiryu
-JSON
-Kjell
-Krech
-kwargs
-Limberg
-MacOS
-Magne
-MAILTO
-makeExtension
-Manfed
-markdownFromFile
-Maruku
-md
-metadata
-MkDocs
-multi
-MultiMarkdown
-munge
-namespace
-NanoDOM
-Neale
-nosetests
-OrderedDict
-OrderedDicts
-OSX
-ol
-Ph
-PHP
-Posix
-postprocessor
-postprocessors
-prepend
-prepended
-preprocessor
-preprocessors
-Pygments
-PyPI
-PyPy
-PYTHONPATH
-PyTidyLib
-PyYAML
-rc
-refactor
-refactored
-refactors
-registerExtension
-richeland
-RSS
-rST
-ryneeverett
-sanitizer
-sanitizers
-Sauder
-schemeless
-setuptools
-Sergej
-serializer
-serializers
-Shachnev
-sitemap
-slugify
-SmartyPants
-Sourceforge
-StackOverflow
-Stansifer
-stdout
-Stelios
-Stienstra
-subclasses
-SuperFences
-svn
-Swartz
-Szakmeister
-Takteyev
-Tiago
-toc
-tokenized
-tox
-Trac
-traceback
-Tredinnick
-Treeprocessor
-Treeprocessors
-tuple
-tuples
-unclosed
-unescape
-unescaping
-unittest
-unordered
-untrusted
-UTF
-uTidylib
-versa
-versioning
-Waylan
-whitelist
-whitespace
-WikiLink
-WikiLinks
-Wolever
-workflow
-Xanthakis
-XHTML
-xhtml
-YAML
-Yunusov
-inline
-wiki
-JavaScript
-plugin
-plugins
-configs
-pre
+++ /dev/null
-# Contributor Code of Conduct
-
-As contributors and maintainers of this project, and in the interest of
-fostering an open and welcoming community, we pledge to respect all people who
-contribute through reporting issues, posting feature requests, updating
-documentation, submitting pull requests or patches, and other activities.
-
-We are committed to making participation in this project a harassment-free
-experience for everyone, regardless of level of experience, gender, gender
-identity and expression, sexual orientation, disability, personal appearance,
-body size, race, ethnicity, age, religion, or nationality.
-
-Examples of unacceptable behavior by participants include:
-
-* The use of sexualized language or imagery
-* Personal attacks
-* Trolling or insulting/derogatory comments
-* Public or private harassment
-* Publishing other's private information, such as physical or electronic
- addresses, without explicit permission
-* Other unethical or unprofessional conduct
-
-Project maintainers have the right and responsibility to remove, edit, or
-reject comments, commits, code, wiki edits, issues, and other contributions
-that are not aligned to this Code of Conduct, or to ban temporarily or
-permanently any contributor for other behaviors that they deem inappropriate,
-threatening, offensive, or harmful.
-
-By adopting this Code of Conduct, project maintainers commit themselves to
-fairly and consistently applying these principles to every aspect of managing
-this project. Project maintainers who do not follow or enforce the Code of
-Conduct may be permanently removed from the project team.
-
-This Code of Conduct applies both within project spaces and in public spaces
-when an individual is representing the project or its community.
-
-Instances of abusive, harassing, or otherwise unacceptable behavior may be
-reported by contacting a project maintainer at python.markdown@gmail.com. All
-complaints will be reviewed and investigated and will result in a response that
-is deemed necessary and appropriate to the circumstances. Maintainers are
-obligated to maintain confidentiality with regard to the reporter of an
-incident.
-
-This Code of Conduct is adapted from the [Contributor Covenant][homepage],
-version 1.3.0, available at
-[https://www.contributor-covenant.org/version/1/3/0/][version]
-
-[homepage]: https://www.contributor-covenant.org/
-[version]: https://www.contributor-covenant.org/version/1/3/0/
recursive-include markdown *.py
recursive-include docs *
recursive-include tests *.txt *.html *.py
-include setup.py
-include setup.cfg
include makefile
include LICENSE.md
include README.md
include MANIFEST
include *-requirements.txt
include mkdocs.yml
+include tox.ini
--- /dev/null
+Metadata-Version: 2.1
+Name: Markdown
+Version: 3.5.1
+Summary: Python implementation of John Gruber's Markdown.
+Author: Manfred Stienstra, Yuri Takhteyev
+Author-email: Waylan limberg <python.markdown@gmail.com>
+Maintainer: Isaac Muse
+Maintainer-email: Waylan Limberg <python.markdown@gmail.com>
+License: Copyright 2007, 2008 The Python Markdown Project (v. 1.7 and later)
+ Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+ Copyright 2004 Manfred Stienstra (the original version)
+
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * Neither the name of the Python Markdown Project nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE PYTHON MARKDOWN PROJECT ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTORS TO THE PYTHON MARKDOWN PROJECT
+ BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+
+Project-URL: Homepage, https://Python-Markdown.github.io/
+Project-URL: Documentation, https://Python-Markdown.github.io/
+Project-URL: Repository, https://github.com/Python-Markdown/markdown
+Project-URL: Issue Tracker, https://github.com/Python-Markdown/markdown/issues
+Project-URL: Changelog, https://github.com/Python-Markdown/markdown/blob/master/docs/change_log/index.md
+Keywords: markdown,markdown-parser,python-markdown,markdown-to-html
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Communications :: Email :: Filters
+Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries
+Classifier: Topic :: Internet :: WWW/HTTP :: Site Management
+Classifier: Topic :: Software Development :: Documentation
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Topic :: Text Processing :: Filters
+Classifier: Topic :: Text Processing :: Markup :: HTML
+Classifier: Topic :: Text Processing :: Markup :: Markdown
+Requires-Python: >=3.8
+Description-Content-Type: text/markdown
+License-File: LICENSE.md
+Requires-Dist: importlib-metadata>=4.4; python_version < "3.10"
+Provides-Extra: testing
+Requires-Dist: coverage; extra == "testing"
+Requires-Dist: pyyaml; extra == "testing"
+Provides-Extra: docs
+Requires-Dist: mkdocs>=1.5; extra == "docs"
+Requires-Dist: mkdocs-nature>=0.6; extra == "docs"
+Requires-Dist: mdx_gh_links>=0.2; extra == "docs"
+Requires-Dist: mkdocstrings[python]; extra == "docs"
+Requires-Dist: mkdocs-gen-files; extra == "docs"
+Requires-Dist: mkdocs-section-index; extra == "docs"
+Requires-Dist: mkdocs-literate-nav; extra == "docs"
+
+[Python-Markdown][]
+===================
+
+[![Build Status][build-button]][build]
+[![Coverage Status][codecov-button]][codecov]
+[![Latest Version][mdversion-button]][md-pypi]
+[![Python Versions][pyversion-button]][md-pypi]
+[![BSD License][bsdlicense-button]][bsdlicense]
+[![Code of Conduct][codeofconduct-button]][Code of Conduct]
+
+[build-button]: https://github.com/Python-Markdown/markdown/workflows/CI/badge.svg?event=push
+[build]: https://github.com/Python-Markdown/markdown/actions?query=workflow%3ACI+event%3Apush
+[codecov-button]: https://codecov.io/gh/Python-Markdown/markdown/branch/master/graph/badge.svg
+[codecov]: https://codecov.io/gh/Python-Markdown/markdown
+[mdversion-button]: https://img.shields.io/pypi/v/Markdown.svg
+[md-pypi]: https://pypi.org/project/Markdown/
+[pyversion-button]: https://img.shields.io/pypi/pyversions/Markdown.svg
+[bsdlicense-button]: https://img.shields.io/badge/license-BSD-yellow.svg
+[bsdlicense]: https://opensource.org/licenses/BSD-3-Clause
+[codeofconduct-button]: https://img.shields.io/badge/code%20of%20conduct-contributor%20covenant-green.svg?style=flat-square
+[Code of Conduct]: https://github.com/Python-Markdown/markdown/blob/master/CODE_OF_CONDUCT.md
+
+This is a Python implementation of John Gruber's [Markdown][].
+It is almost completely compliant with the reference implementation,
+though there are a few known issues. See [Features][] for information
+on what exactly is supported and what is not. Additional features are
+supported by the [Available Extensions][].
+
+[Python-Markdown]: https://Python-Markdown.github.io/
+[Markdown]: https://daringfireball.net/projects/markdown/
+[Features]: https://Python-Markdown.github.io#Features
+[Available Extensions]: https://Python-Markdown.github.io/extensions
+
+Documentation
+-------------
+
+```bash
+pip install markdown
+```
+```python
+import markdown
+html = markdown.markdown(your_text_string)
+```
+
+For more advanced [installation] and [usage] documentation, see the `docs/` directory
+of the distribution or the project website at <https://Python-Markdown.github.io/>.
+
+[installation]: https://python-markdown.github.io/install/
+[usage]: https://python-markdown.github.io/reference/
+
+See the change log at <https://Python-Markdown.github.io/change_log>.
+
+Support
+-------
+
+You may report bugs, ask for help, and discuss various other issues on the [bug tracker][].
+
+[bug tracker]: https://github.com/Python-Markdown/markdown/issues
+
+Code of Conduct
+---------------
+
+Everyone interacting in the Python-Markdown project's code bases, issue trackers,
+and mailing lists is expected to follow the [Code of Conduct].
--- /dev/null
+INSTALL.md
+LICENSE.md
+MANIFEST.in
+README.md
+makefile
+mkdocs.yml
+pyproject.toml
+tox.ini
+Markdown.egg-info/PKG-INFO
+Markdown.egg-info/SOURCES.txt
+Markdown.egg-info/dependency_links.txt
+Markdown.egg-info/entry_points.txt
+Markdown.egg-info/requires.txt
+Markdown.egg-info/top_level.txt
+docs/authors.md
+docs/changelog.md
+docs/cli.md
+docs/contributing.md
+docs/custom.css
+docs/favicon.ico
+docs/index.md
+docs/install.md
+docs/mkdocstrings.css
+docs/py.png
+docs/reference.md
+docs/test_tools.md
+docs/change_log/index.md
+docs/change_log/release-2.0.md
+docs/change_log/release-2.1.md
+docs/change_log/release-2.2.md
+docs/change_log/release-2.3.md
+docs/change_log/release-2.4.md
+docs/change_log/release-2.5.md
+docs/change_log/release-2.6.md
+docs/extensions/abbreviations.md
+docs/extensions/admonition.md
+docs/extensions/api.md
+docs/extensions/attr_list.md
+docs/extensions/code_hilite.md
+docs/extensions/definition_lists.md
+docs/extensions/extra.md
+docs/extensions/fenced_code_blocks.md
+docs/extensions/footnotes.md
+docs/extensions/index.md
+docs/extensions/legacy_attrs.md
+docs/extensions/legacy_em.md
+docs/extensions/md_in_html.md
+docs/extensions/meta_data.md
+docs/extensions/nl2br.md
+docs/extensions/sane_lists.md
+docs/extensions/smarty.md
+docs/extensions/tables.md
+docs/extensions/toc.md
+docs/extensions/wikilinks.md
+docs/templates/python/nature/attribute.html
+docs/templates/python/nature/class.html
+docs/templates/python/nature/function.html
+docs/templates/python/nature/module.html
+docs/templates/python/nature/docstring/admonition.html
+markdown/__init__.py
+markdown/__main__.py
+markdown/__meta__.py
+markdown/blockparser.py
+markdown/blockprocessors.py
+markdown/core.py
+markdown/htmlparser.py
+markdown/inlinepatterns.py
+markdown/postprocessors.py
+markdown/preprocessors.py
+markdown/serializers.py
+markdown/test_tools.py
+markdown/treeprocessors.py
+markdown/util.py
+markdown/extensions/__init__.py
+markdown/extensions/abbr.py
+markdown/extensions/admonition.py
+markdown/extensions/attr_list.py
+markdown/extensions/codehilite.py
+markdown/extensions/def_list.py
+markdown/extensions/extra.py
+markdown/extensions/fenced_code.py
+markdown/extensions/footnotes.py
+markdown/extensions/legacy_attrs.py
+markdown/extensions/legacy_em.py
+markdown/extensions/md_in_html.py
+markdown/extensions/meta.py
+markdown/extensions/nl2br.py
+markdown/extensions/sane_lists.py
+markdown/extensions/smarty.py
+markdown/extensions/tables.py
+markdown/extensions/toc.py
+markdown/extensions/wikilinks.py
+tests/__init__.py
+tests/test_apis.py
+tests/test_extensions.py
+tests/test_legacy.py
+tests/test_meta.py
+tests/basic/amps-and-angle-encoding.html
+tests/basic/amps-and-angle-encoding.txt
+tests/basic/angle-links-and-img.html
+tests/basic/angle-links-and-img.txt
+tests/basic/auto-links.html
+tests/basic/auto-links.txt
+tests/basic/backlash-escapes.html
+tests/basic/backlash-escapes.txt
+tests/basic/blockquotes-with-code-blocks.html
+tests/basic/blockquotes-with-code-blocks.txt
+tests/basic/codeblock-in-list.html
+tests/basic/codeblock-in-list.txt
+tests/basic/hard-wrapped.html
+tests/basic/hard-wrapped.txt
+tests/basic/horizontal-rules.html
+tests/basic/horizontal-rules.txt
+tests/basic/links-inline.html
+tests/basic/links-inline.txt
+tests/basic/links-reference.html
+tests/basic/links-reference.txt
+tests/basic/literal-quotes.html
+tests/basic/literal-quotes.txt
+tests/basic/markdown-documentation-basics.html
+tests/basic/markdown-documentation-basics.txt
+tests/basic/markdown-syntax.html
+tests/basic/markdown-syntax.txt
+tests/basic/nested-blockquotes.html
+tests/basic/nested-blockquotes.txt
+tests/basic/ordered-and-unordered-list.html
+tests/basic/ordered-and-unordered-list.txt
+tests/basic/strong-and-em-together.html
+tests/basic/strong-and-em-together.txt
+tests/basic/tabs.html
+tests/basic/tabs.txt
+tests/basic/tidyness.html
+tests/basic/tidyness.txt
+tests/extensions/admonition.html
+tests/extensions/admonition.txt
+tests/extensions/attr_list.html
+tests/extensions/attr_list.txt
+tests/extensions/codehilite.html
+tests/extensions/codehilite.txt
+tests/extensions/github_flavored.html
+tests/extensions/github_flavored.txt
+tests/extensions/nl2br_w_attr_list.html
+tests/extensions/nl2br_w_attr_list.txt
+tests/extensions/sane_lists.html
+tests/extensions/sane_lists.txt
+tests/extensions/toc.html
+tests/extensions/toc.txt
+tests/extensions/toc_invalid.html
+tests/extensions/toc_invalid.txt
+tests/extensions/toc_nested.html
+tests/extensions/toc_nested.txt
+tests/extensions/toc_nested2.html
+tests/extensions/toc_nested2.txt
+tests/extensions/toc_nested_list.html
+tests/extensions/toc_nested_list.txt
+tests/extensions/toc_out_of_order.html
+tests/extensions/toc_out_of_order.txt
+tests/extensions/wikilinks.html
+tests/extensions/wikilinks.txt
+tests/extensions/extra/def-in-list.html
+tests/extensions/extra/def-in-list.txt
+tests/extensions/extra/extra_config.html
+tests/extensions/extra/extra_config.txt
+tests/extensions/extra/footnote.html
+tests/extensions/extra/footnote.txt
+tests/extensions/extra/footnote_many_footnotes.html
+tests/extensions/extra/footnote_many_footnotes.txt
+tests/extensions/extra/footnote_placeholder.html
+tests/extensions/extra/footnote_placeholder.txt
+tests/extensions/extra/footnote_placeholder_depth.html
+tests/extensions/extra/footnote_placeholder_depth.txt
+tests/extensions/extra/loose_def_list.html
+tests/extensions/extra/loose_def_list.txt
+tests/extensions/extra/markdown-syntax.html
+tests/extensions/extra/markdown-syntax.txt
+tests/extensions/extra/named_markers.html
+tests/extensions/extra/named_markers.txt
+tests/extensions/extra/raw-html.html
+tests/extensions/extra/raw-html.txt
+tests/extensions/extra/simple_def-lists.html
+tests/extensions/extra/simple_def-lists.txt
+tests/misc/CRLF_line_ends.html
+tests/misc/CRLF_line_ends.txt
+tests/misc/adjacent-headers.html
+tests/misc/adjacent-headers.txt
+tests/misc/arabic.html
+tests/misc/arabic.txt
+tests/misc/autolinks_with_asterisks.html
+tests/misc/autolinks_with_asterisks.txt
+tests/misc/autolinks_with_asterisks_russian.html
+tests/misc/autolinks_with_asterisks_russian.txt
+tests/misc/backtick-escape.html
+tests/misc/backtick-escape.txt
+tests/misc/bidi.html
+tests/misc/bidi.txt
+tests/misc/blank-block-quote.html
+tests/misc/blank-block-quote.txt
+tests/misc/blank_lines_in_codeblocks.html
+tests/misc/blank_lines_in_codeblocks.txt
+tests/misc/blockquote-below-paragraph.html
+tests/misc/blockquote-below-paragraph.txt
+tests/misc/blockquote-hr.html
+tests/misc/blockquote-hr.txt
+tests/misc/blockquote.html
+tests/misc/blockquote.txt
+tests/misc/bold_links.html
+tests/misc/bold_links.txt
+tests/misc/br.html
+tests/misc/br.txt
+tests/misc/bracket_re.html
+tests/misc/bracket_re.txt
+tests/misc/brackets-in-img-title.html
+tests/misc/brackets-in-img-title.txt
+tests/misc/code-first-line.html
+tests/misc/code-first-line.txt
+tests/misc/em-around-links.html
+tests/misc/em-around-links.txt
+tests/misc/em_strong.html
+tests/misc/em_strong.txt
+tests/misc/em_strong_complex.html
+tests/misc/em_strong_complex.txt
+tests/misc/email.html
+tests/misc/email.txt
+tests/misc/escaped_links.html
+tests/misc/escaped_links.txt
+tests/misc/funky-list.html
+tests/misc/funky-list.txt
+tests/misc/h1.html
+tests/misc/h1.txt
+tests/misc/hash.html
+tests/misc/hash.txt
+tests/misc/header-in-lists.html
+tests/misc/header-in-lists.txt
+tests/misc/headers.html
+tests/misc/headers.txt
+tests/misc/hline.html
+tests/misc/hline.txt
+tests/misc/image-2.html
+tests/misc/image-2.txt
+tests/misc/image_in_links.html
+tests/misc/image_in_links.txt
+tests/misc/ins-at-start-of-paragraph.html
+tests/misc/ins-at-start-of-paragraph.txt
+tests/misc/inside_html.html
+tests/misc/inside_html.txt
+tests/misc/japanese.html
+tests/misc/japanese.txt
+tests/misc/lazy-block-quote.html
+tests/misc/lazy-block-quote.txt
+tests/misc/link-with-parenthesis.html
+tests/misc/link-with-parenthesis.txt
+tests/misc/lists.html
+tests/misc/lists.txt
+tests/misc/lists2.html
+tests/misc/lists2.txt
+tests/misc/lists3.html
+tests/misc/lists3.txt
+tests/misc/lists4.html
+tests/misc/lists4.txt
+tests/misc/lists5.html
+tests/misc/lists5.txt
+tests/misc/lists6.html
+tests/misc/lists6.txt
+tests/misc/lists7.html
+tests/misc/lists7.txt
+tests/misc/lists8.html
+tests/misc/lists8.txt
+tests/misc/missing-link-def.html
+tests/misc/missing-link-def.txt
+tests/misc/multi-paragraph-block-quote.html
+tests/misc/multi-paragraph-block-quote.txt
+tests/misc/multi-test.html
+tests/misc/multi-test.txt
+tests/misc/nested-lists.html
+tests/misc/nested-lists.txt
+tests/misc/nested-patterns.html
+tests/misc/nested-patterns.txt
+tests/misc/normalize.html
+tests/misc/normalize.txt
+tests/misc/numeric-entity.html
+tests/misc/numeric-entity.txt
+tests/misc/para-with-hr.html
+tests/misc/para-with-hr.txt
+tests/misc/russian.html
+tests/misc/russian.txt
+tests/misc/smart_em.html
+tests/misc/smart_em.txt
+tests/misc/some-test.html
+tests/misc/some-test.txt
+tests/misc/span.html
+tests/misc/span.txt
+tests/misc/strong-with-underscores.html
+tests/misc/strong-with-underscores.txt
+tests/misc/stronintags.html
+tests/misc/stronintags.txt
+tests/misc/tabs-in-lists.html
+tests/misc/tabs-in-lists.txt
+tests/misc/two-spaces.html
+tests/misc/two-spaces.txt
+tests/misc/uche.html
+tests/misc/uche.txt
+tests/misc/underscores.html
+tests/misc/underscores.txt
+tests/misc/url_spaces.html
+tests/misc/url_spaces.txt
+tests/pl/Tests_2004/Amps and angle encoding.html
+tests/pl/Tests_2004/Auto links.html
+tests/pl/Tests_2004/Backslash escapes.html
+tests/pl/Tests_2004/Blockquotes with code blocks.html
+tests/pl/Tests_2004/Hard-wrapped paragraphs with list-like lines.html
+tests/pl/Tests_2004/Horizontal rules.html
+tests/pl/Tests_2004/Inline HTML (Advanced).html
+tests/pl/Tests_2004/Inline HTML (Simple).html
+tests/pl/Tests_2004/Inline HTML comments.html
+tests/pl/Tests_2004/Links, inline style.html
+tests/pl/Tests_2004/Links, reference style.html
+tests/pl/Tests_2004/Literal quotes in titles.html
+tests/pl/Tests_2004/Markdown Documentation - Basics.html
+tests/pl/Tests_2004/Markdown Documentation - Syntax.html
+tests/pl/Tests_2004/Nested blockquotes.html
+tests/pl/Tests_2004/Ordered and unordered lists.html
+tests/pl/Tests_2004/Strong and em together.html
+tests/pl/Tests_2004/Tabs.html
+tests/pl/Tests_2004/Tidyness.html
+tests/pl/Tests_2004/Yuri-Attributes.html
+tests/pl/Tests_2004/Yuri-Email.html
+tests/pl/Tests_2004/Yuri-Footnotes.html
+tests/pl/Tests_2004/Yuri-Links-in-Headers.html
+tests/pl/Tests_2007/Amps and angle encoding.html
+tests/pl/Tests_2007/Auto links.html
+tests/pl/Tests_2007/Backslash escapes.html
+tests/pl/Tests_2007/Blockquotes with code blocks.html
+tests/pl/Tests_2007/Code Blocks.html
+tests/pl/Tests_2007/Code Spans.html
+tests/pl/Tests_2007/Hard-wrapped paragraphs with list-like lines.html
+tests/pl/Tests_2007/Horizontal rules.html
+tests/pl/Tests_2007/Images.html
+tests/pl/Tests_2007/Inline HTML (Advanced).html
+tests/pl/Tests_2007/Inline HTML (Simple).html
+tests/pl/Tests_2007/Inline HTML comments.html
+tests/pl/Tests_2007/Links, inline style.html
+tests/pl/Tests_2007/Links, reference style.html
+tests/pl/Tests_2007/Links, shortcut references.html
+tests/pl/Tests_2007/Literal quotes in titles.html
+tests/pl/Tests_2007/Markdown Documentation - Basics.html
+tests/pl/Tests_2007/Markdown Documentation - Syntax.html
+tests/pl/Tests_2007/Nested blockquotes.html
+tests/pl/Tests_2007/Ordered and unordered lists.html
+tests/pl/Tests_2007/Strong and em together.html
+tests/pl/Tests_2007/Tabs.html
+tests/pl/Tests_2007/Tidyness.html
+tests/test_syntax/__init__.py
+tests/test_syntax/blocks/__init__.py
+tests/test_syntax/blocks/test_blockquotes.py
+tests/test_syntax/blocks/test_code_blocks.py
+tests/test_syntax/blocks/test_headers.py
+tests/test_syntax/blocks/test_hr.py
+tests/test_syntax/blocks/test_html_blocks.py
+tests/test_syntax/blocks/test_paragraphs.py
+tests/test_syntax/extensions/__init__.py
+tests/test_syntax/extensions/test_abbr.py
+tests/test_syntax/extensions/test_admonition.py
+tests/test_syntax/extensions/test_attr_list.py
+tests/test_syntax/extensions/test_code_hilite.py
+tests/test_syntax/extensions/test_def_list.py
+tests/test_syntax/extensions/test_fenced_code.py
+tests/test_syntax/extensions/test_footnotes.py
+tests/test_syntax/extensions/test_legacy_attrs.py
+tests/test_syntax/extensions/test_legacy_em.py
+tests/test_syntax/extensions/test_md_in_html.py
+tests/test_syntax/extensions/test_smarty.py
+tests/test_syntax/extensions/test_tables.py
+tests/test_syntax/extensions/test_toc.py
+tests/test_syntax/inline/__init__.py
+tests/test_syntax/inline/test_autolinks.py
+tests/test_syntax/inline/test_emphasis.py
+tests/test_syntax/inline/test_entities.py
+tests/test_syntax/inline/test_images.py
+tests/test_syntax/inline/test_links.py
+tests/test_syntax/inline/test_raw_html.py
\ No newline at end of file
--- /dev/null
+[console_scripts]
+markdown_py = markdown.__main__:run
+
+[markdown.extensions]
+abbr = markdown.extensions.abbr:AbbrExtension
+admonition = markdown.extensions.admonition:AdmonitionExtension
+attr_list = markdown.extensions.attr_list:AttrListExtension
+codehilite = markdown.extensions.codehilite:CodeHiliteExtension
+def_list = markdown.extensions.def_list:DefListExtension
+extra = markdown.extensions.extra:ExtraExtension
+fenced_code = markdown.extensions.fenced_code:FencedCodeExtension
+footnotes = markdown.extensions.footnotes:FootnoteExtension
+legacy_attrs = markdown.extensions.legacy_attrs:LegacyAttrExtension
+legacy_em = markdown.extensions.legacy_em:LegacyEmExtension
+md_in_html = markdown.extensions.md_in_html:MarkdownInHtmlExtension
+meta = markdown.extensions.meta:MetaExtension
+nl2br = markdown.extensions.nl2br:Nl2BrExtension
+sane_lists = markdown.extensions.sane_lists:SaneListExtension
+smarty = markdown.extensions.smarty:SmartyExtension
+tables = markdown.extensions.tables:TableExtension
+toc = markdown.extensions.toc:TocExtension
+wikilinks = markdown.extensions.wikilinks:WikiLinkExtension
--- /dev/null
+
+[:python_version < "3.10"]
+importlib-metadata>=4.4
+
+[docs]
+mkdocs>=1.5
+mkdocs-nature>=0.6
+mdx_gh_links>=0.2
+mkdocstrings[python]
+mkdocs-gen-files
+mkdocs-section-index
+mkdocs-literate-nav
+
+[testing]
+coverage
+pyyaml
--- /dev/null
+Metadata-Version: 2.1
+Name: Markdown
+Version: 3.5.1
+Summary: Python implementation of John Gruber's Markdown.
+Author: Manfred Stienstra, Yuri Takhteyev
+Author-email: Waylan limberg <python.markdown@gmail.com>
+Maintainer: Isaac Muse
+Maintainer-email: Waylan Limberg <python.markdown@gmail.com>
+License: Copyright 2007, 2008 The Python Markdown Project (v. 1.7 and later)
+ Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+ Copyright 2004 Manfred Stienstra (the original version)
+
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * Neither the name of the Python Markdown Project nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE PYTHON MARKDOWN PROJECT ''AS IS'' AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTORS TO THE PYTHON MARKDOWN PROJECT
+ BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+
+Project-URL: Homepage, https://Python-Markdown.github.io/
+Project-URL: Documentation, https://Python-Markdown.github.io/
+Project-URL: Repository, https://github.com/Python-Markdown/markdown
+Project-URL: Issue Tracker, https://github.com/Python-Markdown/markdown/issues
+Project-URL: Changelog, https://github.com/Python-Markdown/markdown/blob/master/docs/change_log/index.md
+Keywords: markdown,markdown-parser,python-markdown,markdown-to-html
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Communications :: Email :: Filters
+Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries
+Classifier: Topic :: Internet :: WWW/HTTP :: Site Management
+Classifier: Topic :: Software Development :: Documentation
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Topic :: Text Processing :: Filters
+Classifier: Topic :: Text Processing :: Markup :: HTML
+Classifier: Topic :: Text Processing :: Markup :: Markdown
+Requires-Python: >=3.8
+Description-Content-Type: text/markdown
+License-File: LICENSE.md
+Requires-Dist: importlib-metadata>=4.4; python_version < "3.10"
+Provides-Extra: testing
+Requires-Dist: coverage; extra == "testing"
+Requires-Dist: pyyaml; extra == "testing"
+Provides-Extra: docs
+Requires-Dist: mkdocs>=1.5; extra == "docs"
+Requires-Dist: mkdocs-nature>=0.6; extra == "docs"
+Requires-Dist: mdx_gh_links>=0.2; extra == "docs"
+Requires-Dist: mkdocstrings[python]; extra == "docs"
+Requires-Dist: mkdocs-gen-files; extra == "docs"
+Requires-Dist: mkdocs-section-index; extra == "docs"
+Requires-Dist: mkdocs-literate-nav; extra == "docs"
+
+[Python-Markdown][]
+===================
+
+[![Build Status][build-button]][build]
+[![Coverage Status][codecov-button]][codecov]
+[![Latest Version][mdversion-button]][md-pypi]
+[![Python Versions][pyversion-button]][md-pypi]
+[![BSD License][bsdlicense-button]][bsdlicense]
+[![Code of Conduct][codeofconduct-button]][Code of Conduct]
+
+[build-button]: https://github.com/Python-Markdown/markdown/workflows/CI/badge.svg?event=push
+[build]: https://github.com/Python-Markdown/markdown/actions?query=workflow%3ACI+event%3Apush
+[codecov-button]: https://codecov.io/gh/Python-Markdown/markdown/branch/master/graph/badge.svg
+[codecov]: https://codecov.io/gh/Python-Markdown/markdown
+[mdversion-button]: https://img.shields.io/pypi/v/Markdown.svg
+[md-pypi]: https://pypi.org/project/Markdown/
+[pyversion-button]: https://img.shields.io/pypi/pyversions/Markdown.svg
+[bsdlicense-button]: https://img.shields.io/badge/license-BSD-yellow.svg
+[bsdlicense]: https://opensource.org/licenses/BSD-3-Clause
+[codeofconduct-button]: https://img.shields.io/badge/code%20of%20conduct-contributor%20covenant-green.svg?style=flat-square
+[Code of Conduct]: https://github.com/Python-Markdown/markdown/blob/master/CODE_OF_CONDUCT.md
+
+This is a Python implementation of John Gruber's [Markdown][].
+It is almost completely compliant with the reference implementation,
+though there are a few known issues. See [Features][] for information
+on what exactly is supported and what is not. Additional features are
+supported by the [Available Extensions][].
+
+[Python-Markdown]: https://Python-Markdown.github.io/
+[Markdown]: https://daringfireball.net/projects/markdown/
+[Features]: https://Python-Markdown.github.io#Features
+[Available Extensions]: https://Python-Markdown.github.io/extensions
+
+Documentation
+-------------
+
+```bash
+pip install markdown
+```
+```python
+import markdown
+html = markdown.markdown(your_text_string)
+```
+
+For more advanced [installation] and [usage] documentation, see the `docs/` directory
+of the distribution or the project website at <https://Python-Markdown.github.io/>.
+
+[installation]: https://python-markdown.github.io/install/
+[usage]: https://python-markdown.github.io/reference/
+
+See the change log at <https://Python-Markdown.github.io/change_log>.
+
+Support
+-------
+
+You may report bugs, ask for help, and discuss various other issues on the [bug tracker][].
+
+[bug tracker]: https://github.com/Python-Markdown/markdown/issues
+
+Code of Conduct
+---------------
+
+Everyone interacting in the Python-Markdown project's code bases, issue trackers,
+and mailing lists is expected to follow the [Code of Conduct].
Code of Conduct
---------------
-Everyone interacting in the Python-Markdown project's codebases, issue trackers,
+Everyone interacting in the Python-Markdown project's code bases, issue trackers,
and mailing lists is expected to follow the [Code of Conduct].
+++ /dev/null
-#!/bin/bash
-
-echo "Checking links in documentation..."
-
-# List of files in docs dir
-docs=$(find . -path './docs/*.md')
-# List of files in project root (README, etc)
-extras=$(find . -maxdepth 1 -name '*.md')
-# Combined list of files to check
-files=("${docs[@]}" "${extras[@]}")
-
-let "fails=0"
-let "count=0"
-
-for file in ${files[@]}; do
- let "count++"
- markdown-link-check -q "$file"
- if [ $? -ne 0 ]; then
- let "fails++"
- fi
-done
-
-echo -e "\n\033[0;33m$count files checked."
-
-if [ $fails -gt 0 ]; then
- echo -e "\033[0;31mERROR: $fails files with dead links found!"
- exit 1
-else
- echo -e "\033[0;32mCongratulations! No dead links found."
- exit 0
-fi
+++ /dev/null
-#!/bin/bash
-
-echo "Building docs..."
-mkdocs build --strict
-if [ $? -ne 0 ]; then
- exit 1
-fi
-echo "Compiling Dictionary..."
-aspell --lang=en create master ./tmp <.spell-dict
-if [ $? -ne 0 ]; then
- exit 1
-fi
-echo "Checking spelling..."
-
-let "fails=0"
-
-for file in $(find site/ -type f -name "*.html"); do
- words=$(aspell list --lang=en --mode=html --add-html-skip=code --extra-dicts=./tmp <$file)
- if [ "$words" ]; then
- uniquewords=$(tr ' ' '\n' <<< "${words[@]}" | sort -u | tr '\n' ' ')
- let "fails++"
- echo "Misspelled words in '$file':"
- echo "-----------------------------------------------------------------"
- for word in ${uniquewords[@]}; do
- echo $word
- done
- echo "-----------------------------------------------------------------"
- fi
-done
-rm -f ./tmp
-rm -rf site
-
-if [ $fails -gt 0 ]; then
- echo "$fails files with misspelled words."
- exit 1
-else
- exit 0
-fi
+++ /dev/null
-mkdocs>=1.0
-mkdocs-nature
and has been assisting with maintenance, reviewing pull requests and ticket
triage.
-* __[Yuri Takteyev](https://github.com/yuri)__
+* __[Yuri Takhteyev](https://github.com/yuri)__
Yuri wrote most of the code found in version 1.x while procrastinating his
Ph.D. Various pieces of his code still exist, most notably the basic
Python-Markdown Change Log
=========================
-May 5, 2022: version 3.3.7 (a bug-fix release).
+!!! note
-* Disallow square brackets in reference link ids (#1209).
-* Retain configured `pygments_style` after first code block (#1240).
-* Ensure fenced code attributes are properly escaped (#1247).
-
-Nov 17, 2021: version 3.3.6 (a bug-fix release).
-
-* Fix a dependency issue (#1195, #1196).
-
-Nov 16, 2021: version 3.3.5 (a bug-fix release).
-
-* Make the `slugify_unicode` function not remove diacritical marks (#1118).
-* Fix `[toc]` detection when used with `nl2br` extension (#1160).
-* Re-use compiled regex for block level checks (#1169).
-* Don't process shebangs in fenced code blocks when using CodeHilite (#1156).
-* Improve email address validation for Automatic Links (#1165).
-* Ensure `<summary>` tags are parsed correctly (#1079).
-* Support Python 3.10 (#1124).
-
-Feb 24, 2021: version 3.3.4 (a bug-fix release).
-
-* Properly parse unclosed tags in code spans (#1066).
-* Properly parse processing instructions in md_in_html (#1070).
-* Properly parse code spans in md_in_html (#1069).
-* Preserve text immediately before an admonition (#1092).
-* Simplified regex for HTML placeholders (#928) addressing (#932).
-* Ensure `permalinks` and `anchorlinks` are not restricted by `toc_depth` (#1107).
-* Fix corner cases with lists under admonitions (#1102).
-
-Oct 25, 2020: version 3.3.3 (a bug-fix release).
-
-* Unify all block-level tags (#1047).
-* Fix issue where some empty elements would have text rendered as `None` when using `md_in_html` (#1049).
-* Avoid catastrophic backtracking in `hr` regex (#1055).
-* Fix `hr` HTML handling (#1053).
-
-Oct 19, 2020: version 3.3.2 (a bug-fix release).
-
-* Properly parse inline HTML in md_in_html (#1040 & #1045).
-* Avoid crashing when md_in_html fails (#1040).
-
-Oct 12, 2020: version 3.3.1 (a bug-fix release).
-
-* Correctly parse raw `script` and `style` tags (#1036).
-* Ensure consistent class handling by `fenced_code` and `codehilite` (#1032).
-
-Oct 6, 2020: version 3.3 ([Notes](release-3.3.md)).
-
-May 8, 2020: version 3.2.2 (a bug-fix release).
-
-* Add `checklinks` tox environment to ensure all links in documentation are good.
-* Refactor extension API documentation (#729).
-* Load entry_points (for extensions) only once using `importlib.metadata`.
-* Do not double escape entities in TOC.
-* Correctly report if an extension raises a `TypeError` (#939).
-* Raise a `KeyError` when attempting to delete a nonexistent key from the
- extension registry (#939).
-* Remove import of `packaging` (or `pkg_resources` fallback) entirely.
-* Remove `setuptools` as a run-time dependency (`install_required`).
-
-Feb 12, 2020: Released version 3.2.1 (a bug-fix release).
-
-* The `name` property in `toc_tokens` from the TOC extension now
- escapes HTML special characters (`<`, `>`, and `&`).
-
-Feb 7, 2020: Released version 3.2 ([Notes](release-3.2.md)).
-
-May 20, 2019: Released version 3.1.1 (a bug-fix release).
-
-* Fixed import failure in `setup.py` when the source directory is not
- on `sys.path` (#823).
-* Prefer public `packaging` module to pkg_resources' private copy of
- it (#825).
-
-Mar 25, 2019: Released version 3.1 ([Notes](release-3.1.md)).
-
-Sept 28, 2018: Released version 3.0.1 (a bug-fix release).
-
-* Brought back the `version` and `version_info` variables (#709).
-* Added support for hexadecimal HTML entities (#712).
-
-Sept 21, 2018: Released version 3.0 ([Notes](release-3.0.md)).
+ This is an archive of the changelog prior to the release of version 3.0. See the [current changelog](../changelog.md) for up-to-date details.
Jan 4, 2018: Released version 2.6.11 (a bug-fix release). Added a new
`BACKLINK-TITLE` option to the footnote extension so that non-English
and moved all extensions into a 'markdown-extensions' package.
Added additional documentation and a few bug fixes. (v2.0-beta)
-August 4 2008: Updated included extensions to ElementTree. Added a
+August 4 2008: Updated included extensions to `ElementTree`. Added a
separate command line script. (v2.0-alpha)
-July 2008: Switched from home-grown NanoDOM to ElementTree and
+July 2008: Switched from home-grown `NanoDOM` to `ElementTree` and
various related bugs (thanks Artem Yunusov).
June 2008: Fixed issues with nested inline patterns and cleaned
correctly (v. 0.8)
Aug. 29, 2005: Added flexible tabs, fixed a few small issues, added
-basic support for footnotes. Got rid of xml.dom.minidom and added
+basic support for footnotes. Got rid of `xml.dom.minidom` and added
pretty-printing. (v. 0.7)
Aug. 13, 2005: Fixed a number of small bugs in order to conform to the
+++ /dev/null
-title: Release Notes for v3.0
-
-# Python-Markdown 3.0 Release Notes
-
-We are pleased to release Python-Markdown 3.0 which adds a few new features and
-fixes various bugs and deprecates various old features. See the list of changes
-below for details.
-
-Python-Markdown version 3.0 supports Python versions 2.7, 3.4, 3.5, 3.6, 3.7,
-PyPy and PyPy3.
-
-## Backwards-incompatible changes
-
-### `enable_attributes` keyword deprecated
-
-The `enable_attributes` keyword is deprecated in version 3.0 and will be
-ignored. Previously the keyword was `True` by default and enabled an
-undocumented way to define attributes on document elements. The feature has been
-removed from version 3.0. As most users did not use the undocumented feature, it
-should not affect most users. For the few who did use the feature, it can be
-enabled by using the [Legacy Attributes](../extensions/legacy_attrs.md)
-extension.
-
-### `smart_emphasis` keyword and `smart_strong` extension deprecated
-
-The `smart_emphasis` keyword is deprecated in version 3.0 and will be ignored.
-Previously the keyword was `True` by default and caused the parser to ignore
-middle-word emphasis. Additionally, the optional `smart_strong` extension
-provided the same behavior for strong emphasis. Both of those features are now
-part of the default behavior, and the [Legacy
-Emphasis](../extensions/legacy_em.md) extension is available to disable that
-behavior.
-
-### `output_formats` simplified to `html` and `xhtml`.
-
-The `output_formats` keyword now only accepts two options: `html` and `xhtml`
-Note that if `(x)html1`, `(x)html4` or `(x)html5` are passed in, the number is
-stripped and ignored.
-
-### `safe_mode` and `html_replacement_text` keywords deprecated
-
-Both `safe_mode` and the associated `html_replacement_text` keywords are
-deprecated in version 3.0 and will be ignored. The so-called "safe mode" was
-never actually "safe" which has resulted in many people having a false sense of
-security when using it. As an alternative, the developers of Python-Markdown
-recommend that any untrusted content be passed through an HTML sanitizer (like
-[Bleach]) after being converted to HTML by markdown. In fact, [Bleach Whitelist]
-provides a curated list of tags, attributes, and styles suitable for filtering
-user-provided HTML using bleach.
-
-If your code previously looked like this:
-
-```python
-html = markdown.markdown(text, safe_mode=True)
-```
-
-Then it is recommended that you change your code to read something like this:
-
-```python
-import bleach
-from bleach_whitelist import markdown_tags, markdown_attrs
-html = bleach.clean(markdown.markdown(text), markdown_tags, markdown_attrs)
-```
-
-If you are not interested in sanitizing untrusted text, but simply desire to
-escape raw HTML, then that can be accomplished through an extension which
-removes HTML parsing:
-
-```python
-from markdown.extensions import Extension
-
-class EscapeHtml(Extension):
- def extendMarkdown(self, md):
- md.preprocessors.deregister('html_block')
- md.inlinePatterns.deregister('html')
-
-html = markdown.markdown(text, extensions=[EscapeHtml()])
-```
-
-As the HTML would not be parsed with the above Extension, then the serializer
-will escape the raw HTML, which is exactly what happened in previous versions
-with `safe_mode="escape"`.
-
-[Bleach]: https://bleach.readthedocs.io/
-[Bleach Whitelist]: https://github.com/yourcelf/bleach-whitelist
-
-### Positional arguments deprecated
-
-Positional arguments on the `markdown.Markdown()` class are deprecated as are
-all except the `text` argument on the `markdown.markdown()` wrapper function.
-Using positional arguments will raise an error. Only keyword arguments should be
-used. For example, if your code previously looked like this:
-
-```python
-html = markdown.markdown(text, [SomeExtension()])
-```
-
-Then it is recommended that you change it to read something like this:
-
-```python
-html = markdown.markdown(text, extensions=[SomeExtension()])
-```
-
-!!! Note
- This change is being made as a result of deprecating `"safe_mode"` as the
- `safe_mode` argument was one of the positional arguments. When that argument
- is removed, the two arguments following it will no longer be at the correct
- position. It is recommended that you always use keywords when they are
- supported for this reason.
-
-### Extension name behavior has changed
-
-In previous versions of Python-Markdown, the built-in extensions received
-special status and did not require the full path to be provided. Additionally,
-third party extensions whose name started with `"mdx_"` received the same
-special treatment. This is no longer the case.
-
-Support has been added for extensions to define an [entry
-point](../extensions/api.md#entry_point). An entry point is a string name which
-can be used to point to an `Extension` class. The built-in extensions now have
-entry points which match the old short names. And any third-party extensions
-which define entry points can now get the same behavior. See the documentation
-for each specific extension to find the assigned name.
-
-If an extension does not define an entry point, then the full path to the
-extension must be used. See the [documentation](../reference.md#extensions) for
-a full explanation of the current behavior.
-
-### Extension configuration as part of extension name deprecated
-
-The previously documented method of appending the extension configuration
-options as a string to the extension name is deprecated and will raise an error.
-The [`extension_configs`](../reference.md#extension_configs) keyword should be
-used instead. See the [documentation](../reference.md#extension_configs) for a
-full explanation of the current behavior.
-
-### HeaderId extension deprecated
-
-The HeaderId Extension is deprecated and will raise an error if specified. Use
-the [Table of Contents](../extensions/toc.md) Extension instead, which offers
-most of the features of the HeaderId Extension and more (support for meta data
-is missing).
-
-Extension authors who have been using the `slugify` and `unique` functions
-defined in the HeaderId Extension should note that those functions are now
-defined in the Table of Contents extension and should adjust their import
-statements accordingly (`from markdown.extensions.toc import slugify, unique`).
-
-### Homegrown `OrderedDict` has been replaced with a purpose-built `Registry`
-
-All processors and patterns now get "registered" to a
-[Registry](../extensions/api.md#registry). A backwards compatible shim is
-included so that existing simple extensions should continue to work.
-A `DeprecationWarning` will be raised for any code which calls the old API.
-
-### Markdown class instance references.
-
-Previously, instances of the `Markdown` class were represented as any one of
-`md`, `md_instance`, or `markdown`. This inconsistency made it difficult when
-developing extensions, or just maintaining the existing code. Now, all instances
-are consistently represented as `md`.
-
-The old attributes on class instances still exist, but raise a
-`DeprecationWarning` when accessed. Also on classes where the instance was
-optional, the attribute always exists now and is simply `None` if no instance
-was provided (previously the attribute would not exist).
-
-### `markdown.util.isBlockLevel` deprecated
-
-The `markdown.util.isBlockLevel` function is deprecated and will raise a
-`DeprecationWarning`. Instead, extensions should use the `isBlockLevel` method
-of the `Markdown` class instance. Additionally, a list of block level elements
-is defined in the `block_level_elements` attribute of the `Markdown` class which
-extensions can access to alter the list of elements which are treated as block
-level elements.
-
-### `md_globals` keyword deprecated from extension API
-
-Previously, the `extendMarkdown` method of a `markdown.extensions.Extension`
-subclasses accepted an `md_globals` keyword, which contained the value returned
-by Python's `globals()` built-in function. As all of the configuration is now
-held within the `Markdown` class instance, access to the globals is no longer
-necessary and any extensions which expect the keyword will raise a
-`DeprecationWarning`. A future release will raise an error.
-
-### `markdown.version` and `markdown.version_info` deprecated
-
-Historically, version numbers were acquired via the attributes
-`markdown.version` and `markdown.version_info`. Moving forward, a more
-standardized approach is being followed and versions are acquired via the
-`markdown.__version__` and `markdown.__version_info__` attributes. The legacy
-attributes are still available to allow distinguishing versions between the
-legacy Markdown 2.0 series and the Markdown 3.0 series, but in the future the
-legacy attributes will be removed.
-
-### Added new, more flexible `InlineProcessor` class
-
-A new `InlineProcessor` class handles inline processing much better and allows
-for more flexibility. The new `InlineProcessor` classes no longer utilize
-unnecessary pretext and post-text captures. New class can accept the buffer that
-is being worked on and manually process the text without regular expressions and
-return new replacement bounds. This helps us to handle links in a better way and
-handle nested brackets and logic that is too much for regular expression.
-
-## New features
-
-The following new features have been included in the release:
-
-* A new [testing framework](../test_tools.md) is included as a part of the
- Markdown library, which can also be used by third party extensions.
-
-* A new `toc_depth` parameter has been added to the
- [Table of Contents Extension](../extensions/toc.md).
-
-* A new `toc_tokens` attribute has been added to the Markdown class by the
- [Table of Contents Extension](../extensions/toc.md), which contains the raw
- tokens used to build the Table of Contents. Users can use this to build their
- own custom Table of Contents rather than needing to parse the HTML available
- on the `toc` attribute of the Markdown class.
-
-* When the [Table of Contents Extension](../extensions/toc.md) is used in
- conjunction with the [Attribute Lists Extension](../extensions/attr_list.md)
- and a `data-toc-label` attribute is defined on a header, the content of the
- `data-toc-label` attribute is now used as the content of the Table of Contents
- item for that header.
-
-* Additional CSS class names can be appended to
- [Admonitions](../extensions/admonition.md).
+++ /dev/null
-title: Release Notes for v3.1
-
-# Python-Markdown 3.1 Release Notes
-
-Python-Markdown version 3.1 supports Python versions 2.7, 3.5, 3.6, 3.7,
-PyPy and PyPy3.
-
-## Backwards-incompatible changes
-
-### `markdown.version` and `markdown.version_info` deprecated
-
-Historically, version numbers were acquired via the attributes
-`markdown.version` and `markdown.version_info`. As of 3.0, a more standardized
-approach is being followed and versions are acquired via the
-`markdown.__version__` and `markdown.__version_info__` attributes. As of 3.1
-the legacy attributes will raise a `DeprecationWarning` if they are accessed. In
-a future release the legacy attributes will be removed.
-
-## New features
-
-The following new features have been included in the release:
-
-* A [Contributing Guide](../contributing.md) has been added (#732).
-
-* A new configuration option to set the footnote separator has been added. Also,
- the `rel` and `rev` attributes have been removed from footnotes as they are
- not valid in HTML5. The `refs` and `backrefs` classes already exist and
- serve the same purpose (#723).
-
-* A new option for `toc_depth` to set not only the bottom section level,
- but also the top section level. A string consisting of two digits
- separated by a hyphen in between (`"2-5"`), defines the top (`t`) and the
- bottom (`b`) (`<ht>..<hb>`). A single integer still defines the bottom
- section level (`<h1>..<hb>`) only. (#787).
-
-## Bug fixes
-
-The following bug fixes are included in the 3.1 release:
-
-* Update CLI to support PyYAML 5.1.
-* Overlapping raw HTML matches no longer leave placeholders behind (#458).
-* Emphasis patterns now recognize newline characters as whitespace (#783).
-* Version format had been updated to be PEP 440 compliant (#736).
-* Block level elements are defined per instance, not as class attributes
- (#731).
-* Double escaping of block code has been eliminated (#725).
-* Problems with newlines in references has been fixed (#742).
-* Escaped `#` are now handled in header syntax (#762).
+++ /dev/null
-title: Release Notes for v3.2
-
-# Python-Markdown 3.2 Release Notes
-
-Python-Markdown version 3.2 supports Python versions 3.5, 3.6, 3.7, 3.8, and
-PyPy3.
-
-## Backwards-incompatible changes
-
-### Drop support for Python 2.7
-
-Python 2.7 reaches end-of-life on 2020-01-01 and Python-Markdown 3.2 has dropped
-support for it. Please upgrade to Python 3, or use Python-Markdown 3.1.
-
-### `em` and `strong` inline processor changes
-
-In order to fix issue #792, `em`/`strong` inline processors were refactored. This
-translated into removing many of the existing inline processors that handled this
-logic:
-
-* `em_strong`
-* `strong`
-* `emphasis`
-* `strong2`
-* `emphasis`
-
-These processors were replaced with two new ones:
-
-* `em_strong`
-* `em_strong2`
-
-The [`legacy_em`](../extensions/legacy_em.md) extension was also modified with new,
-refactored logic and simply overrides the `em_strong2` inline processor.
-
-### CodeHilite now always wraps with `<code>` tags
-
-Before, the HTML generated by CodeHilite looked like:
-- `<pre><code>foo = 'bar'</code></pre>` if you **were not** using Pygments.
-- `<pre>foo = 'bar'</pre>` if you **were** using Pygments.
-
-To make the cases more consistent (and adhere to many Markdown specifications and
-HTML code block markup suggestions), CodeHilite will now always additionally wrap
-code with `<code>` tags. See #862 for more details.
-
-This change does not alter the Python-Markdown API, but users relying on the old
-markup will find their output now changed.
-
-Internally, this change relies on the Pygments 2.4, so you must be using at least
-that version to see this effect. Users with earlier Pygments versions will
-continue to see the old behavior.
-
-### `markdown.util.etree` deprecated
-
-Previously, Python-Markdown was using either the `xml.etree.cElementTree` module
-or the `xml.etree.ElementTree` module, based on their availability. In modern
-Python versions, the former is a deprecated alias for the latter. Thus, the
-compatibility layer is deprecated and extensions are advised to use
-`xml.etree.ElementTree` directly. Importing `markdown.util.etree` will raise
-a `DeprecationWarning` beginning in version 3.2 and may be removed in a future
-release.
-
-Therefore, extension developers are encouraged to replace
-`from markdown.util import etree` with
-`import xml.etree.ElementTree as etree` in their code.
-
-## New features
-
-The following new features have been included in the release:
-
-* Some new configuration options have been added to the [toc](../extensions/toc.md)
- extension:
-
- * The `anchorlink_class` and `permalink_class` options allow class(es) to be
- assigned to the `anchorlink` and `permalink` respectively. This allows using
- icon fonts from CSS for the links. Therefore, an empty string passed to
- `permalink` now generates an empty `permalink`. Previously no `permalink`
- would have been generated. (#776)
-
- * The `permalink_title` option allows the title attribute of a `permalink` to be
- set to something other than the default English string `Permanent link`. (#877)
-
-* Document thread safety (#812).
-
-* Markdown parsing in HTML has been exposed via a separate extension called
- [`md_in_html`](../extensions/md_in_html.md).
-
-* Add support for Python 3.8.
-
-## Bug fixes
-
-The following bug fixes are included in the 3.2 release:
-
-* HTML tag placeholders are no longer included in `.toc_tokens` (#899).
-* Unescape backslash-escaped characters in TOC ids (#864).
-* Refactor bold and italic logic in order to solve complex nesting issues (#792).
-* Always wrap CodeHilite code in `code` tags (#862).
+++ /dev/null
-title: Release Notes for v3.3
-
-# Python-Markdown 3.3 Release Notes
-
-Python-Markdown version 3.3 supports Python versions 3.6, 3.7, 3.8, 3.9 and PyPy3.
-
-## Backwards-incompatible changes
-
-### The prefix `language-` is now prepended to all language classes by default on code blocks.
-
-The [HTML5 spec][spec] recommends that the class defining the language of a code block be prefixed with `language-`.
-Therefore, by default, both the [fenced_code] and [codehilite] extensions now prepend the prefix when code
-highlighting is disabled.
-
-If you have previously been including the prefix manually in your fenced code blocks, then you will not want a second
-instance of the prefix. Similarly, if you are using a third party syntax highlighting tool which does not recognize
-the prefix, or requires a different prefix, then you will want to redefine the prefix globally using the `lang_prefix`
-configuration option of either the `fenced_code` or `codehilite` extensions.
-
-For example, to configure `fenced_code` to not apply any prefix (the previous behavior), set the option to an empty string:
-
-```python
-from markdown.extensions.fenced_code import FencedCodeExtension
-
-markdown.markdown(src, extensions=[FencedCodeExtension(lang_prefix='')])
-```
-
-!!! note
- When code highlighting is [enabled], the output from Pygments is used unaltered. Currently, Pygments does not
- provide an option to include the language class in the output, let alone prefix it. Therefore, any language prefix
- is only applied when syntax highlighting is disabled.
-
-### Attribute Lists are more strict (#898).
-
-Empty curly braces are now completely ignored by the [Attribute List] extension. Previously, the extension would
-recognize them as attribute lists and remove them from the document. Therefore, it is no longer necessary to backslash
-escape a set of curly braces which are empty or only contain whitespace.
-
-Despite not being documented, previously an attribute list could be defined anywhere within a table cell and get
-applied to the cell (`<td>` element). Now the attribute list must be defined at the end of the cell content and must
-be separated from the rest of the content by at least one space. This makes it easy to differentiate between attribute
-lists defined on inline elements within a cell and the attribute list for the cell itself. It is also more consistent
-with how attribute lists are defined on other types of elements.
-
-The extension has also added support for defining attribute lists on table header cells (`<th>` elements) in the same
-manner as data cells (`<td>` elements).
-
-In addition, the documentation for the extensions received an overhaul. The features (#987) and limitations (#965) of the extension are now fully documented.
-
-## New features
-
-The following new features have been included in the 3.3 release:
-
-* All Pygments' options are now available for syntax highlighting (#816).
- - The [Codehilite](../extensions/code_hilite.md) extension now accepts any options
- which Pygments supports as global configuration settings on the extension.
- - [Fenced Code Blocks](../extensions/fenced_code_blocks.md) will accept any of the
- same options on individual code blocks.
- - Any of the previously supported aliases to Pygments' options continue to be
- supported at this time. However, it is recommended that the Pygments option names
- be used directly to ensure continued compatibility in the future.
-
-* [Fenced Code Blocks](../extensions/fenced_code_blocks.md) now work with
- [Attribute Lists](../extensions/attr_list.md) when syntax highlighting is disabled.
- Any random HTML attribute can be defined and set on the `<code>` tag of fenced code
- blocks when the `attr_list` extension is enabled (#816).
-
-* The HTML parser has been completely replaced. The new HTML parser is built on Python's
- [html.parser.HTMLParser](https://docs.python.org/3/library/html.parser.html), which
- alleviates various bugs and simplify maintenance of the code (#803, #830).
-
-* The [Markdown in HTML](../extensions/md_in_html.md) extension has been rebuilt on the
- new HTML Parser, which drastically simplifies it. Note that raw HTML elements with a
- `markdown` attribute defined are now converted to ElementTree Elements and are rendered
- by the serializer. Various bugs have been fixed (#803, #595, #780, and #1012).
-
-* Link reference parsing, abbreviation reference parsing and footnote reference parsing
- has all been moved from `preprocessors` to `blockprocessors`, which allows them to be
- nested within other block level elements. Specifically, this change was necessary to
- maintain the current behavior in the rebuilt Markdown in HTML extension. A few random
- edge-case bugs (see the included tests) were resolved in the process (#803).
-
-* An alternate function `markdown.extensions.headerid.slugify_unicode` has been included
- with the [Table of Contents](../extensions/toc.md) extension which supports Unicode
- characters in table of contents slugs. The old `markdown.extensions.headerid.slugify`
- method which removes non-ASCII characters remains the default. Import and pass
- `markdown.extensions.headerid.slugify_unicode` to the `slugify` configuration option
- to use the new behavior.
-
-* Support was added for Python 3.9 and dropped for Python 3.5.
-
-## Bug fixes
-
-The following bug fixes are included in the 3.3 release:
-
-* Document how to pass configuration options to Extra (#1019).
-* Fix HR which follows strong em (#897).
-* Support short reference image links (#894).
-* Avoid a `RecursionError` from deeply nested blockquotes (#799).
-* Fix issues with complex emphasis (#979).
-* Fix unescaping of HTML characters `<>` in CodeHilite (#990).
-* Fix complex scenarios involving lists and admonitions (#1004).
-* Fix complex scenarios with nested ordered and unordered lists in a definition list (#918).
-
-[spec]: https://www.w3.org/TR/html5/text-level-semantics.html#the-code-element
-[fenced_code]: ../extensions/fenced_code_blocks.md
-[codehilite]: ../extensions/code_hilite.md
-[enabled]: ../extensions/fenced_code_blocks.md#enabling-syntax-highlighting
-[Attribute List]: ../extensions/attr_list.md
--- /dev/null
+title: Changelog
+toc_depth: 2
+
+# Python-Markdown Changelog
+
+All notable changes to this project will be documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). See the [Contributing Guide](contributing.md) for details.
+
+## [3.5.1] -- 2023-10-31
+
+### Fixed
+
+* Fix a performance problem with HTML extraction where large HTML input could
+ trigger quadratic line counting behavior (#1392).
+* Improve and expand type annotations in the code base (#1394).
+
+## [3.5] -- 2023-10-06
+
+### Added
+
+#### Add `permalink_leading` configuration option to the toc extension (#1339)
+
+A new boolean option `permalink_leading` controls the position of the permanent
+link anchors generated with `permalink`. Setting `permalink_leading` to `True`
+will cause the links to be inserted at the start of the header, before any other
+header content. The default behavior for `permalink` is to append permanent
+links to the header, placing them after all other header content.
+
+### Changed
+
+* Add support for cPython version 3.12 (and PyPy 3.10) and drop support for
+ Python version 3.7 (#1357).
+* Refactor changelog to use the format defined at <https://keepachangelog.com/>.
+* Update the list of empty HTML tags (#1353).
+* Add customizable TOC title class to TOC extension (#1293).
+* Add API documentation of the code base which is generated by
+ [mkdocstrings](https://mkdocstrings.github.io/) (#1220).
+
+### Fixed
+
+* Fix a corner case in admonitions where if an indented code block was provided
+ as the first block, the output would be malformed (#1329).
+
+## [3.4.4] -- 2023-07-25
+
+### Fixed
+
+* Add a special case for initial `'s` to smarty extension (#1305).
+* Unescape any backslash escaped inline raw HTML (#1358).
+* Unescape backslash escaped TOC token names (#1360).
+
+## [3.4.3] -- 2023-03-23
+
+### Fixed
+
+* Restore console script (#1327).
+
+## [3.4.2] -- 2023-03-22
+
+### Fixed
+* Officially support Python 3.11.
+* Improve standalone * and _ parsing (#1300).
+* Consider `<html>` HTML tag a block-level element (#1309).
+* Switch from `setup.py` to `pyproject.toml`.
+
+## [3.4.1] -- 2022-07-15
+
+### Fixed
+
+* Fix an import issue with `importlib.util` (#1274).
+
+## [3.4] -- 2022-07-15
+
+### Changed
+
+#### The `tables` extension now uses a `style` attribute instead of an `align` attribute for alignment.
+
+The [HTML4 spec](https://www.w3.org/TR/html4/present/graphics.html#h-15.1.2)
+specifically deprecates the use of the `align` attribute and it does not appear
+at all in the [HTML5
+spec](https://www.w3.org/TR/html53/tabular-data.html#attributes-common-to-td-and-th-elements).
+Therefore, by default, the [tables](extensions/tables.md) extension will now use
+the `style` attribute (setting just the `text-align` property) in `td` and `th`
+blocks.
+
+The former behavior is available by setting the `use_align_attribute`
+configuration option to `True` when enabling the extension.
+
+For example, to configure the old `align` behavior:
+
+```python
+from markdown.extensions.tables import TableExtension
+
+markdown.markdown(src, extensions=[TableExtension(use_align_attribute=True)])
+```
+
+#### Backslash unescaping moved to Treeprocessor (#1131).
+
+Unescaping backslash escapes has been moved to a Treeprocessor, which enables
+proper HTML escaping during serialization. However, it is recognized that
+various third-party extensions may be calling the old class at
+`postprocessors.UnescapePostprocessor`. Therefore, the old class remains in the
+code base, but has been deprecated and will be removed in a future release. The
+new class `treeprocessors.UnescapeTreeprocessor` should be used instead.
+
+#### Previously deprecated objects have been removed
+
+Various objects were deprecated in version 3.0 and began raising deprecation
+warnings (see the [version 3.0 release notes](#30-2018-09-21) for details). Any of those objects
+which remained in version 3.3 have been removed from the code base in version 3.4
+and will now raise errors. The relevant objects are listed below.
+
+
+| Deprecated Object | Replacement Object |
+|----------------------------------------|-------------------------------------|
+| `markdown.version` | `markdown.__version__` |
+| `markdown.version_info` | `markdown.__version_info__` |
+| `markdown.util.etree` | `xml.etree.ElementTree` |
+| `markdown.util.string_type` | `str` |
+| `markdown.util.text_type` | `str` |
+| `markdown.util.int2str` | `chr` |
+| `markdown.util.iterrange` | `range` |
+| `markdown.util.isBlockLevel` | `markdown.Markdown().is_block_level`|
+| `markdown.util.Processor().markdown` | `markdown.util.Processor().md` |
+| `markdown.util.Registry().__setitem__` | `markdown.util.Registry().register` |
+| `markdown.util.Registry().__delitem__` |`markdown.util.Registry().deregister`|
+| `markdown.util.Registry().add` | `markdown.util.Registry().register` |
+
+In addition, the `md_globals` parameter of
+`Markdown.extensions.Extension.extendMarkdown()` is no longer recognized as a
+valid parameter and will raise an error if provided.
+
+### Added
+
+* Some new configuration options have been added to the
+ [footnotes](extensions/footnotes.md) extension (#1218):
+
+ * Small refactor of the `BACKLINK_TITLE` option; The use of `format()`
+ instead of "old" `%d` formatter allows one to specify text without the
+ need to have the number of the footnote in it (like footnotes on
+ Wikipedia for example). The modification is backward compatible so no
+ configuration change is required.
+
+ * Addition of a new option `SUPERSCRIPT_TEXT` that allows one to specify a
+ custom placeholder for the footnote itself in the text.
+ Ex: `[{}]` will give `<sup>[1]</sup>`, `({})` will give `<sup>(1)</sup>`,
+ or by default, the current behavior: `<sup>1</sup>`.
+
+* The [Table of Contents](extensions/toc.md) extension now accepts a
+ `toc_class` parameter which can be used to set the CSS class(es) on the
+ `<div>` that contains the Table of Contents (#1224).
+
+* The CodeHilite extension now supports a `pygments_formatter` option that can
+ be set to a custom formatter class (#1187).
+
+ - If `pygments_formatter` is set to a string (ex: `'html'`), Pygments'
+ default formatter by that name is used.
+ - If `pygments_formatter` is set to a formatter class (or any callable
+ which returns a formatter instance), then an instance of that class is
+ used.
+
+ The formatter class is now passed an additional option, `lang_str`, to
+ denote the language of the code block (#1258). While Pygments' built-in
+ formatters will ignore the option, a custom formatter assigned to the
+ `pygments_formatter` option can make use of the `lang_str` to include the
+ code block's language in the output.
+
+### Fixed
+
+* Extension entry-points are only loaded if needed (#1216).
+* Added additional checks to the `<pre><code>` handling of
+ `PrettifyTreeprocessor` (#1261, #1263).
+* Fix XML deprecation warnings.
+
+## [3.3.7] -- 2022-05-05
+
+### Fixed
+
+* Disallow square brackets in reference link ids (#1209).
+* Retain configured `pygments_style` after first code block (#1240).
+* Ensure fenced code attributes are properly escaped (#1247).
+
+## [3.3.6] -- 2021-11-17
+
+### Fixed
+
+* Fix a dependency issue (#1195, #1196).
+
+## [3.3.5] -- 2021-11-16
+
+### Fixed
+
+* Make the `slugify_unicode` function not remove diacritical marks (#1118).
+* Fix `[toc]` detection when used with `nl2br` extension (#1160).
+* Re-use compiled regex for block level checks (#1169).
+* Don't process shebangs in fenced code blocks when using CodeHilite (#1156).
+* Improve email address validation for Automatic Links (#1165).
+* Ensure `<summary>` tags are parsed correctly (#1079).
+* Support Python 3.10 (#1124).
+
+## [3.3.4] -- 2021-02-24
+
+### Fixed
+
+* Properly parse unclosed tags in code spans (#1066).
+* Properly parse processing instructions in md_in_html (#1070).
+* Properly parse code spans in md_in_html (#1069).
+* Preserve text immediately before an admonition (#1092).
+* Simplified regex for HTML placeholders (#928) addressing (#932).
+* Ensure `permalinks` and `anchorlinks` are not restricted by `toc_depth` (#1107).
+* Fix corner cases with lists under admonitions (#1102).
+
+## [3.3.3] -- 2020-10-25
+
+### Fixed
+
+* Unify all block-level tags (#1047).
+* Fix issue where some empty elements would have text rendered as `None` when using `md_in_html` (#1049).
+* Avoid catastrophic backtracking in `hr` regex (#1055).
+* Fix `hr` HTML handling (#1053).
+
+## [3.3.2] -- 2020-10-19
+
+### Fixed
+
+* Properly parse inline HTML in md_in_html (#1040 & #1045).
+* Avoid crashing when md_in_html fails (#1040).
+
+## [3.3.1] -- 2020-10-12
+
+### Fixed
+
+* Correctly parse raw `script` and `style` tags (#1036).
+* Ensure consistent class handling by `fenced_code` and `codehilite` (#1032).
+
+## [3.3] -- 2020-10-06
+
+### Changed
+
+#### The prefix `language-` is now prepended to all language classes by default on code blocks.
+
+The [HTML5
+spec](https://www.w3.org/TR/html5/text-level-semantics.html#the-code-element)
+recommends that the class defining the language of a code block be prefixed with
+`language-`. Therefore, by default, both the
+[fenced_code](extensions/fenced_code_blocks.md) and
+[codehilite](extensions/code_hilite.md) extensions now prepend the prefix when
+code highlighting is disabled.
+
+If you have previously been including the prefix manually in your fenced code blocks, then you will not want a second
+instance of the prefix. Similarly, if you are using a third party syntax highlighting tool which does not recognize
+the prefix, or requires a different prefix, then you will want to redefine the prefix globally using the `lang_prefix`
+configuration option of either the `fenced_code` or `codehilite` extensions.
+
+For example, to configure `fenced_code` to not apply any prefix (the previous behavior), set the option to an empty string:
+
+```python
+from markdown.extensions.fenced_code import FencedCodeExtension
+
+markdown.markdown(src, extensions=[FencedCodeExtension(lang_prefix='')])
+```
+
+!!! note
+ When code highlighting is
+ [enabled](extensions/fenced_code_blocks.md#enabling-syntax-highlighting),
+ the output from Pygments is used unaltered. Currently, Pygments does not
+ provide an option to include the language class in the output, let alone
+ prefix it. Therefore, any language prefix is only applied when syntax
+ highlighting is disabled.
+
+#### Attribute Lists are more strict (#898).
+
+Empty curly braces are now completely ignored by the [Attribute List](extensions/attr_list.md) extension. Previously, the extension would
+recognize them as attribute lists and remove them from the document. Therefore, it is no longer necessary to backslash
+escape a set of curly braces which are empty or only contain whitespace.
+
+Despite not being documented, previously an attribute list could be defined anywhere within a table cell and get
+applied to the cell (`<td>` element). Now the attribute list must be defined at the end of the cell content and must
+be separated from the rest of the content by at least one space. This makes it easy to differentiate between attribute
+lists defined on inline elements within a cell and the attribute list for the cell itself. It is also more consistent
+with how attribute lists are defined on other types of elements.
+
+The extension has also added support for defining attribute lists on table header cells (`<th>` elements) in the same
+manner as data cells (`<td>` elements).
+
+In addition, the documentation for the extensions received an overhaul. The features (#987) and limitations (#965) of the extension are now fully documented.
+
+### Added
+
+* All Pygments' options are now available for syntax highlighting (#816).
+ - The [Codehilite](extensions/code_hilite.md) extension now accepts any options
+ which Pygments supports as global configuration settings on the extension.
+ - [Fenced Code Blocks](extensions/fenced_code_blocks.md) will accept any of the
+ same options on individual code blocks.
+ - Any of the previously supported aliases to Pygments' options continue to be
+ supported at this time. However, it is recommended that the Pygments option names
+ be used directly to ensure continued compatibility in the future.
+
+* [Fenced Code Blocks](extensions/fenced_code_blocks.md) now work with
+ [Attribute Lists](extensions/attr_list.md) when syntax highlighting is disabled.
+ Any random HTML attribute can be defined and set on the `<code>` tag of fenced code
+ blocks when the `attr_list` extension is enabled (#816).
+
+* The HTML parser has been completely replaced. The new HTML parser is built on Python's
+ [`html.parser.HTMLParser`](https://docs.python.org/3/library/html.parser.html), which
+ alleviates various bugs and simplify maintenance of the code (#803, #830).
+
+* The [Markdown in HTML](extensions/md_in_html.md) extension has been rebuilt on the
+ new HTML Parser, which drastically simplifies it. Note that raw HTML elements with a
+ `markdown` attribute defined are now converted to ElementTree Elements and are rendered
+ by the serializer. Various bugs have been fixed (#803, #595, #780, and #1012).
+
+* Link reference parsing, abbreviation reference parsing and footnote reference parsing
+ has all been moved from `preprocessors` to `blockprocessors`, which allows them to be
+ nested within other block level elements. Specifically, this change was necessary to
+ maintain the current behavior in the rebuilt Markdown in HTML extension. A few random
+ edge-case bugs (see the included tests) were resolved in the process (#803).
+
+* An alternate function `markdown.extensions.headerid.slugify_unicode` has been included
+ with the [Table of Contents](extensions/toc.md) extension which supports Unicode
+ characters in table of contents slugs. The old `markdown.extensions.headerid.slugify`
+ method which removes non-ASCII characters remains the default. Import and pass
+ `markdown.extensions.headerid.slugify_unicode` to the `slugify` configuration option
+ to use the new behavior.
+
+* Support was added for Python 3.9 and dropped for Python 3.5.
+
+### Fixed
+
+* Document how to pass configuration options to Extra (#1019).
+* Fix HR which follows strong em (#897).
+* Support short reference image links (#894).
+* Avoid a `RecursionError` from deeply nested blockquotes (#799).
+* Fix issues with complex emphasis (#979).
+* Fix unescaping of HTML characters `<>` in CodeHilite (#990).
+* Fix complex scenarios involving lists and admonitions (#1004).
+* Fix complex scenarios with nested ordered and unordered lists in a definition list (#918).
+
+## [3.2.2] -- 2020-05-08
+
+### Fixed
+
+* Add `checklinks` tox environment to ensure all links in documentation are good.
+* Refactor extension API documentation (#729).
+* Load entry_points (for extensions) only once using `importlib.metadata`.
+* Do not double escape entities in TOC.
+* Correctly report if an extension raises a `TypeError` (#939).
+* Raise a `KeyError` when attempting to delete a nonexistent key from the
+ extension registry (#939).
+* Remove import of `packaging` (or `pkg_resources` fallback) entirely.
+* Remove `setuptools` as a run-time dependency (`install_required`).
+
+## [3.2.1] -- 2020-02-12
+
+### Fixed
+
+* The `name` property in `toc_tokens` from the TOC extension now
+ escapes HTML special characters (`<`, `>`, and `&`).
+
+## [3.2] -- 2020-02-07
+
+### Changed
+
+#### Drop support for Python 2.7
+
+Python 2.7 reaches end-of-life on 2020-01-01 and Python-Markdown 3.2 has dropped
+support for it. Please upgrade to Python 3, or use Python-Markdown 3.1.
+
+#### `em` and `strong` inline processor changes
+
+In order to fix issue #792, `em`/`strong` inline processors were refactored. This
+translated into removing many of the existing inline processors that handled this
+logic:
+
+* `em_strong`
+* `strong`
+* `emphasis`
+* `strong2`
+* `emphasis`
+
+These processors were replaced with two new ones:
+
+* `em_strong`
+* `em_strong2`
+
+The [`legacy_em`](extensions/legacy_em.md) extension was also modified with new,
+refactored logic and simply overrides the `em_strong2` inline processor.
+
+#### CodeHilite now always wraps with `<code>` tags
+
+Before, the HTML generated by CodeHilite looked like:
+- `<pre><code>foo = 'bar'</code></pre>` if you **were not** using Pygments.
+- `<pre>foo = 'bar'</pre>` if you **were** using Pygments.
+
+To make the cases more consistent (and adhere to many Markdown specifications and
+HTML code block markup suggestions), CodeHilite will now always additionally wrap
+code with `<code>` tags. See #862 for more details.
+
+This change does not alter the Python-Markdown API, but users relying on the old
+markup will find their output now changed.
+
+Internally, this change relies on the Pygments 2.4, so you must be using at least
+that version to see this effect. Users with earlier Pygments versions will
+continue to see the old behavior.
+
+#### `markdown.util.etree` deprecated
+
+Previously, Python-Markdown was using either the `xml.etree.cElementTree` module
+or the `xml.etree.ElementTree` module, based on their availability. In modern
+Python versions, the former is a deprecated alias for the latter. Thus, the
+compatibility layer is deprecated and extensions are advised to use
+`xml.etree.ElementTree` directly. Importing `markdown.util.etree` will raise
+a `DeprecationWarning` beginning in version 3.2 and may be removed in a future
+release.
+
+Therefore, extension developers are encouraged to replace
+`from markdown.util import etree` with
+`import xml.etree.ElementTree as etree` in their code.
+
+### Added
+
+* Some new configuration options have been added to the [toc](extensions/toc.md)
+ extension:
+
+ * The `anchorlink_class` and `permalink_class` options allow class(es) to be
+ assigned to the `anchorlink` and `permalink` respectively. This allows using
+ icon fonts from CSS for the links. Therefore, an empty string passed to
+ `permalink` now generates an empty `permalink`. Previously no `permalink`
+ would have been generated. (#776)
+
+ * The `permalink_title` option allows the title attribute of a `permalink` to be
+ set to something other than the default English string `Permanent link`. (#877)
+
+* Document thread safety (#812).
+
+* Markdown parsing in HTML has been exposed via a separate extension called
+ [`md_in_html`](extensions/md_in_html.md).
+
+* Add support for Python 3.8.
+
+### Fixed
+
+* HTML tag placeholders are no longer included in `.toc_tokens` (#899).
+* Unescape backslash-escaped characters in TOC ids (#864).
+* Refactor bold and italic logic in order to solve complex nesting issues (#792).
+* Always wrap CodeHilite code in `code` tags (#862).
+
+## [3.1.1] -- 2019-05-20
+
+### Fixed
+
+* Fixed import failure in `setup.py` when the source directory is not
+ on `sys.path` (#823).
+* Prefer public `packaging` module to pkg_resources' private copy of
+ it (#825).
+
+## [3.1] -- 2019-03-25
+
+### Changed
+
+#### `markdown.version` and `markdown.version_info` deprecated
+
+Historically, version numbers were acquired via the attributes
+`markdown.version` and `markdown.version_info`. As of 3.0, a more standardized
+approach is being followed and versions are acquired via the
+`markdown.__version__` and `markdown.__version_info__` attributes. As of 3.1
+the legacy attributes will raise a `DeprecationWarning` if they are accessed. In
+a future release the legacy attributes will be removed.
+
+### Added
+
+* A [Contributing Guide](contributing.md) has been added (#732).
+
+* A new configuration option to set the footnote separator has been added. Also,
+ the `rel` and `rev` attributes have been removed from footnotes as they are
+ not valid in HTML5. The `refs` and `backrefs` classes already exist and
+ serve the same purpose (#723).
+
+* A new option for `toc_depth` to set not only the bottom section level,
+ but also the top section level. A string consisting of two digits
+ separated by a hyphen in between (`"2-5"`), defines the top (`t`) and the
+ bottom (`b`) (`<ht>..<hb>`). A single integer still defines the bottom
+ section level (`<h1>..<hb>`) only. (#787).
+
+### Fixed
+
+* Update CLI to support PyYAML 5.1.
+* Overlapping raw HTML matches no longer leave placeholders behind (#458).
+* Emphasis patterns now recognize newline characters as whitespace (#783).
+* Version format had been updated to be PEP 440 compliant (#736).
+* Block level elements are defined per instance, not as class attributes
+ (#731).
+* Double escaping of block code has been eliminated (#725).
+* Problems with newlines in references has been fixed (#742).
+* Escaped `#` are now handled in header syntax (#762).
+
+## [3.0.1] -- 2018-09-28
+
+### Fixed
+
+* Brought back the `version` and `version_info` variables (#709).
+* Added support for hexadecimal HTML entities (#712).
+
+## [3.0] -- 2018-09-21
+
+### Changed
+
+#### `enable_attributes` keyword deprecated
+
+The `enable_attributes` keyword is deprecated in version 3.0 and will be
+ignored. Previously the keyword was `True` by default and enabled an
+undocumented way to define attributes on document elements. The feature has been
+removed from version 3.0. As most users did not use the undocumented feature, it
+should not affect most users. For the few who did use the feature, it can be
+enabled by using the [Legacy Attributes](extensions/legacy_attrs.md)
+extension.
+
+#### `smart_emphasis` keyword and `smart_strong` extension deprecated
+
+The `smart_emphasis` keyword is deprecated in version 3.0 and will be ignored.
+Previously the keyword was `True` by default and caused the parser to ignore
+middle-word emphasis. Additionally, the optional `smart_strong` extension
+provided the same behavior for strong emphasis. Both of those features are now
+part of the default behavior, and the [Legacy
+Emphasis](extensions/legacy_em.md) extension is available to disable that
+behavior.
+
+#### `output_formats` simplified to `html` and `xhtml`.
+
+The `output_formats` keyword now only accepts two options: `html` and `xhtml`
+Note that if `(x)html1`, `(x)html4` or `(x)html5` are passed in, the number is
+stripped and ignored.
+
+#### `safe_mode` and `html_replacement_text` keywords deprecated
+
+Both `safe_mode` and the associated `html_replacement_text` keywords are
+deprecated in version 3.0 and will be ignored. The so-called "safe mode" was
+never actually "safe" which has resulted in many people having a false sense of
+security when using it. As an alternative, the developers of Python-Markdown
+recommend that any untrusted content be passed through an HTML sanitizer (like
+[Bleach](https://bleach.readthedocs.io/)) after being converted to HTML by
+markdown. In fact, [Bleach
+Whitelist](https://github.com/yourcelf/bleach-whitelist) provides a curated list
+of tags, attributes, and styles suitable for filtering user-provided HTML using
+bleach.
+
+If your code previously looked like this:
+
+```python
+html = markdown.markdown(text, safe_mode=True)
+```
+
+Then it is recommended that you change your code to read something like this:
+
+```python
+import bleach
+from bleach_whitelist import markdown_tags, markdown_attrs
+html = bleach.clean(markdown.markdown(text), markdown_tags, markdown_attrs)
+```
+
+If you are not interested in sanitizing untrusted text, but simply desire to
+escape raw HTML, then that can be accomplished through an extension which
+removes HTML parsing:
+
+```python
+from markdown.extensions import Extension
+
+class EscapeHtml(Extension):
+ def extendMarkdown(self, md):
+ md.preprocessors.deregister('html_block')
+ md.inlinePatterns.deregister('html')
+
+html = markdown.markdown(text, extensions=[EscapeHtml()])
+```
+
+As the HTML would not be parsed with the above Extension, then the serializer
+will escape the raw HTML, which is exactly what happened in previous versions
+with `safe_mode="escape"`.
+
+#### Positional arguments deprecated
+
+Positional arguments on the `markdown.Markdown()` class are deprecated as are
+all except the `text` argument on the `markdown.markdown()` wrapper function.
+Using positional arguments will raise an error. Only keyword arguments should be
+used. For example, if your code previously looked like this:
+
+```python
+html = markdown.markdown(text, [SomeExtension()])
+```
+
+Then it is recommended that you change it to read something like this:
+
+```python
+html = markdown.markdown(text, extensions=[SomeExtension()])
+```
+
+!!! Note
+ This change is being made as a result of deprecating `"safe_mode"` as the
+ `safe_mode` argument was one of the positional arguments. When that argument
+ is removed, the two arguments following it will no longer be at the correct
+ position. It is recommended that you always use keywords when they are
+ supported for this reason.
+
+#### Extension name behavior has changed
+
+In previous versions of Python-Markdown, the built-in extensions received
+special status and did not require the full path to be provided. Additionally,
+third party extensions whose name started with `"mdx_"` received the same
+special treatment. This is no longer the case.
+
+Support has been added for extensions to define an [entry
+point](extensions/api.md#entry_point). An entry point is a string name which
+can be used to point to an `Extension` class. The built-in extensions now have
+entry points which match the old short names. And any third-party extensions
+which define entry points can now get the same behavior. See the documentation
+for each specific extension to find the assigned name.
+
+If an extension does not define an entry point, then the full path to the
+extension must be used. See the [documentation](reference.md#extensions) for
+a full explanation of the current behavior.
+
+#### Extension configuration as part of extension name deprecated
+
+The previously documented method of appending the extension configuration
+options as a string to the extension name is deprecated and will raise an error.
+The [`extension_configs`](reference.md#extension_configs) keyword should be
+used instead. See the [documentation](reference.md#extension_configs) for a
+full explanation of the current behavior.
+
+#### HeaderId extension deprecated
+
+The HeaderId Extension is deprecated and will raise an error if specified. Use
+the [Table of Contents](extensions/toc.md) Extension instead, which offers
+most of the features of the HeaderId Extension and more (support for meta data
+is missing).
+
+Extension authors who have been using the `slugify` and `unique` functions
+defined in the HeaderId Extension should note that those functions are now
+defined in the Table of Contents extension and should adjust their import
+statements accordingly (`from markdown.extensions.toc import slugify, unique`).
+
+#### Homegrown `OrderedDict` has been replaced with a purpose-built `Registry`
+
+All processors and patterns now get "registered" to a
+[Registry](extensions/api.md#registry). A backwards compatible shim is
+included so that existing simple extensions should continue to work.
+A `DeprecationWarning` will be raised for any code which calls the old API.
+
+#### Markdown class instance references.
+
+Previously, instances of the `Markdown` class were represented as any one of
+`md`, `md_instance`, or `markdown`. This inconsistency made it difficult when
+developing extensions, or just maintaining the existing code. Now, all instances
+are consistently represented as `md`.
+
+The old attributes on class instances still exist, but raise a
+`DeprecationWarning` when accessed. Also on classes where the instance was
+optional, the attribute always exists now and is simply `None` if no instance
+was provided (previously the attribute would not exist).
+
+#### `markdown.util.isBlockLevel` deprecated
+
+The `markdown.util.isBlockLevel` function is deprecated and will raise a
+`DeprecationWarning`. Instead, extensions should use the `isBlockLevel` method
+of the `Markdown` class instance. Additionally, a list of block level elements
+is defined in the `block_level_elements` attribute of the `Markdown` class which
+extensions can access to alter the list of elements which are treated as block
+level elements.
+
+#### `md_globals` keyword deprecated from extension API
+
+Previously, the `extendMarkdown` method of a `markdown.extensions.Extension`
+subclasses accepted an `md_globals` keyword, which contained the value returned
+by Python's `globals()` built-in function. As all of the configuration is now
+held within the `Markdown` class instance, access to the globals is no longer
+necessary and any extensions which expect the keyword will raise a
+`DeprecationWarning`. A future release will raise an error.
+
+#### `markdown.version` and `markdown.version_info` deprecated
+
+Historically, version numbers were acquired via the attributes
+`markdown.version` and `markdown.version_info`. Moving forward, a more
+standardized approach is being followed and versions are acquired via the
+`markdown.__version__` and `markdown.__version_info__` attributes. The legacy
+attributes are still available to allow distinguishing versions between the
+legacy Markdown 2.0 series and the Markdown 3.0 series, but in the future the
+legacy attributes will be removed.
+
+#### Added new, more flexible `InlineProcessor` class
+
+A new `InlineProcessor` class handles inline processing much better and allows
+for more flexibility. The new `InlineProcessor` classes no longer utilize
+unnecessary pretext and post-text captures. New class can accept the buffer that
+is being worked on and manually process the text without regular expressions and
+return new replacement bounds. This helps us to handle links in a better way and
+handle nested brackets and logic that is too much for regular expression.
+
+### Added
+
+* A new [testing framework](test_tools.md) is included as a part of the
+ Markdown library, which can also be used by third party extensions.
+
+* A new `toc_depth` parameter has been added to the
+ [Table of Contents Extension](extensions/toc.md).
+
+* A new `toc_tokens` attribute has been added to the Markdown class by the
+ [Table of Contents Extension](extensions/toc.md), which contains the raw
+ tokens used to build the Table of Contents. Users can use this to build their
+ own custom Table of Contents rather than needing to parse the HTML available
+ on the `toc` attribute of the Markdown class.
+
+* When the [Table of Contents Extension](extensions/toc.md) is used in
+ conjunction with the [Attribute Lists Extension](extensions/attr_list.md)
+ and a `data-toc-label` attribute is defined on a header, the content of the
+ `data-toc-label` attribute is now used as the content of the Table of Contents
+ item for that header.
+
+* Additional CSS class names can be appended to
+ [Admonitions](extensions/admonition.md).
+
+## Previous Releases
+
+For information on prior releases, see their changelogs:
+
+* [2.x and earlier](change_log/index.md)
allows us to keep the maintenance overhead of Python-Markdown to a minimum, so
that the focus can be on continued stability, bug fixes, and documentation.
-Closing an issue does not necessarily mean the end of a discussion. If you
-believe your issue has been closed incorrectly, explain why and we'll consider
-if it needs to be reopened.
+If you intend to submit a fix for your bug or provide an implementation of your
+feature request, it is not necessary to first open an issue. You can report a
+bug or make a feature request as part of a pull request. Of course, if you want
+to receive feedback on how to implement a bug-fix or feature before submitting
+a solution, then it would be appropriate to open an issue first and ask your
+questions there.
+
+Having your issue closed does not necessarily mean the end of a discussion. If
+you believe your issue has been closed incorrectly, explain why and we'll
+consider if it needs to be reopened.
## Pull Requests
Before being accepted, each pull request must include the applicable code, new
tests of all new features, updated tests for any changed features, documentation
-updates, and an appropriate update to the release notes. All changes must follow
+updates, and an appropriate update to the changelog. All changes must follow
the applicable style guides. Failure to meet any one of the requirements is
likely to delay any serious consideration of your pull request and may even
cause it to be closed. Of course, if you are in the early stages of development,
fail, you may push additional commits to your branch. GitHub will add those
commits to the pull request and rerun the checks.
+It is generally best not to squash multiple commits and force-push your changes
+to a pull request. Instead, the maintainers would like to be able to follow the
+series of commits along with the discussion about those changes as they
+progress over time. If your pull request is accepted, it will be squashed at
+that time if deemed appropriate.
+
## Style Guides
In an effort to maintain consistency, Python-Markdown adheres to the following
This is the content of the note.
```
+#### Changelog
+
+Any commit/pull request which changes the behavior of the Markdown library in
+any way must include an entry in the changelog. If a change only alters the
+documentation or tooling for the project, then an entry in the changelog is
+not necessary. The current changelog can be found at `docs/changelog.md`.
+
+The current changelog follows the format defined at
+[keepachangelog.com](https://keepachangelog.com/en/1.1.0/). The description of
+each change should include a reference to the relevant GitHub issue in the
+format `#123` (where `123` is the issue number).
+
+Edits to the changelog should generally add entries to the `[unreleased]`
+version at the top of the log. A pull request should not alter an entry for a
+previously released version, unless it is editing an error in the notes for
+that version, or is otherwise expressly deemed appropriate by the project
+maintainers.
+
+The current changelog should only document the changes for one MAJOR release and
+its various MINOR and PATCH releases (see [Versions](#versions) for an
+explanation of MAJOR, MINOR, and PATCH releases). Older versions from previous
+series of releases can be found in the archive at `docs/change_log/` and may
+follow a different format. Note that the archived changelogs are not in the site
+navigation and are only linked from the [Previous
+Releases](changelog.md#previous-releases) section of the current changelog.
+
### Commit Message Style Guide
Use the present tense ("Add feature" not "Added feature").
Reference issues and pull requests liberally after the first line. Include a
summary of the changes/additions made without replicating the content of the
-documentation or release notes. This is where an explanation of the choices made
+documentation or changelog. This is where an explanation of the choices made
should be found. References to issues and pull requests should only provide the
context in which a choice was made. However, the commit should be able to stand
on its own.
virtual environment for the first time:
```sh
-pip install --editable .
+pip install -e .
```
Now any saved changes will immediately be available within the virtual
python -m markdown
```
+Before building the documentation for the first time, you will need to install
+some optional dependencies with the command:
+
+```sh
+pip install -e .[docs]
+```
+
+To build the documentation and serve it locally on a development server, run:
+
+```sh
+mkdocs serve
+```
+
+Then point your browser at `http://127.0.0.1:8000/`. For a complete list of
+options available, view MkDocs' help with the command:
+
+```sh
+mkdocs --help
+```
+
+Before running tests for the first time, you will need to install some optional
+dependencies with the command:
+
+```sh
+pip install -e .[testing]
+```
+
And you can directly run the tests with:
```sh
python -m unittest discover tests
```
+To get a coverage report after running the tests, use these commands instead:
+
+```sh
+coverage run --source=markdown -m unittest discover tests
+coverage report --show-missing
+```
+
!!! note
Some tests require the [PyTidyLib] library, which depends on the [HTML Tidy]
library. If you do not have PyTidyLib installed, the tests which depend upon
it will be skipped. Given the difficulty in installing the HTML Tidy library
on many systems, you may choose to leave both libraries uninstalled and
- depend on the Travis server to run those tests when you submit a pull
- request.
+ depend on the continuous integration server to run those tests when you
+ submit a pull request.
The above setup will only run tests against the code in one version of Python.
However, Python-Markdown supports multiple versions of Python. Therefore, a
[tox] configuration is included in the repository, which includes test
environments for all supported Python versions, a [Flake8] test environment, and
a spellchecker for the documentation. While it is generally fine to leave those
-tests for the Travis server to run when a pull request is submitted, for more
-advanced changes, you may want to run those tests locally. To do so, simply
-install tox:
+tests for the continuous integration server to run when a pull request is
+submitted, for more advanced changes, you may want to run those tests locally.
+To do so, simply install tox:
```sh
pip install tox
!!! seealso "See Also"
- Python-Markdown provides [test tools] which simply testing Markdown syntax.
+ Python-Markdown provides [test tools] which simply test Markdown syntax.
Understanding those tools will often help in understanding why a test may be
failing.
of the `master` branch should always be identified in the `__version_info__`
tuple defined in [`markdown/__meta__.py`][markdown/__meta__.py]. The contents of
that tuple will automatically be converted into a normalized version which
-conforms to [PEP 440]. An invalid `__version_info__` tuple will raise an error,
-preventing the library from running and the package from building.
+conforms to [PEP 440]. Each time the version is changed, the continuous
+integration server will run a test to ensure that the current version is in a
+valid normalized format.
### Version Status
1. Verify that all outstanding issues and pull requests related to the release
have been resolved.
-2. Confirm that the release notes and change log have been updated and indicate
- the date of the new release.
+2. Confirm that the changelog has been updated and indicate the date and
+ version of the new release.
3. Update the version defined in [`markdown/__meta__.py`][markdown/__meta__.py].
- Deploy an update to the documentation using [MkDocs]. The following example
assumes that local clones of the [Python-Markdown/markdown] and
- [Python-Markdown/Python-Markdown.github.io] repositories are in sibling
- directories named `markdown` and `Python-Markdown.github.io` respectively.
+ [`Python-Markdown/Python-Markdown.github.io`][Python-Markdown/Python-Markdown.github.io]
+ repositories are in sibling directories named `markdown` and `Python-Markdown.github.io`
+ respectively.
cd Python-Markdown.github.io
mkdocs gh-deploy --config-file ../markdown/mkdocs.yml --remote-branch master
[tox]: https://tox.readthedocs.io/en/latest/
[aspell]: http://aspell.net/
[test tools]: test_tools.md
-[Semantic Versioning]: https://semver.org/
+[Semantic Versioning]: https://semver.org/spec/v2.0.0.html
[markdown/__meta__.py]: https://github.com/Python-Markdown/markdown/blob/master/markdown/__meta__.py#L29
[PEP 440]: https://www.python.org/dev/peps/pep-0440/
[PyPI]: https://pypi.org/project/Markdown/
--- /dev/null
+div.body h4, div.body h5, div.body h6 {
+ background-color: transparent;
+ padding-left: 0;
+ font-weight: bold;
+}
There is no CSS included as part of this extension. Check out the default
[Sphinx][sphinx] theme for inspiration.
-[sphinx]: https://www.sphinx-doc.org/en/stable/
+[sphinx]: https://www.sphinx-doc.org/en/master/
## Usage
: Add an item to the registry with the given name and priority.
- Parameters:
+ Arguments:
* `item`: The item being registered.
* `name`: A string used to reference the item.
* **`lang_prefix`**{ #lang_prefix }:
The prefix prepended to the language class assigned to the HTML `<code>` tag. Default: `language-`.
- This option only applies when `use_pygments` is `False` as Pygments does not provide an option to include a
- language prefix.
+* **`pygments_formatter`**{ #pygments_formatter }:
+ This option can be used to change the Pygments formatter used for highlighting code blocks. By default, this
+ is set to the string `'html'`, which means it'll use the default `HtmlFormatter` provided by Pygments.
+ This can be set to a string representing any of the other default formatters, or set to a formatter class (or
+ any callable).
+
+ The code's language is always passed to the formatter as an extra option `lang_str`, with the value formatted as
+ `{lang_prefix}{lang}`. If the language is unspecified, the language guessed by Pygments will be used. While
+ this option has no effect to the Pygments's builtin formatters, a user can make use of the language in their custom
+ formatter. See an example below.
+
+ To see what formatters are available and how to subclass an existing formatter, please visit [Pygments
+ documentation on this topic][pygments formatters].
* Any other Pygments' options:
markdown.markdown(some_text, extensions=['codehilite'])
```
+To keep the code block's language in the Pygments generated HTML output, one can provide a custom Pygments formatter
+that takes the `lang_str` option. For example,
+
+```python
+from pygments.formatters import HtmlFormatter
+from markdown.extensions.codehilite import CodeHiliteExtension
+
+
+class CustomHtmlFormatter(HtmlFormatter):
+ def __init__(self, lang_str='', **options):
+ super().__init__(**options)
+ # lang_str has the value {lang_prefix}{lang}
+ # specified by the CodeHilite's options
+ self.lang_str = lang_str
+
+ def _wrap_code(self, source):
+ yield 0, f'<code class="{self.lang_str}">'
+ yield from source
+ yield 0, '</code>'
+
+
+some_text = '''\
+ :::python
+ print('hellow world')
+'''
+
+markdown.markdown(
+ some_text,
+ extensions=[CodeHiliteExtension(pygments_formatter=CustomHtmlFormatter)],
+)
+```
+
+The formatter above will output the following HTML structure for a code block:
+
+```html
+<div class="codehilite">
+ <pre>
+ <code class="language-python">
+ ...
+ </code>
+ </pre>
+</div>
+```
+
[html formatter]: https://pygments.org/docs/formatters/#HtmlFormatter
[lexer]: https://pygments.org/docs/lexers/
[spec]: https://www.w3.org/TR/html5/text-level-semantics.html#the-code-element
+[pygments formatters]: https://pygments.org/docs/formatters/
````
To include a set of backticks (or tildes) within a code block, use a different number of backticks for the
-deliminators.
+delimiters.
`````md
````
The text string that links from the footnote definition back to the position
in the document. Defaults to `↩`.
+* **`SUPERSCRIPT_TEXT`**:
+ The text string that links from the position in the document to the footnote
+ definition. Defaults to `{}`, i.e. only the footnote's number.
+
* **`BACKLINK_TITLE`**:
The text string for the `title` HTML attribute of the footnote definition link.
- `%d` will be replaced by the footnote number. Defaults to `Jump back to
- footnote %d in the text`
+ The placeholder `{}` will be replaced by the footnote number. Defaults to
+ `Jump back to footnote {} in the text`.
* **`SEPARATOR`**:
The text string used to set the footnote separator. Defaults to `:`.
The first blank line ends all meta-data for the document. Therefore, the first
line of a document must not be blank.
-Alternatively, You may use YAML style deliminators to mark the start and/or end
+Alternatively, You may use YAML style delimiters to mark the start and/or end
of your meta-data. When doing so, the first line of your document must be `---`.
The meta-data ends at the first blank line or the first line containing an end
deliminator (either `---` or `...`), whichever comes first. Even though YAML
-deliminators are supported, meta-data is not parsed as YAML.
+delimiters are supported, meta-data is not parsed as YAML.
All meta-data is stripped from the document prior to any further processing
by Markdown.
See [Extensions](index.md) for general extension usage. Use `tables` as the
name of the extension.
-This extension does not accept any special configuration options.
+See the [Library Reference](../reference.md#extensions) for information about
+configuring extensions.
+
+The following options are provided to change the default behavior:
+
+* **`use_align_attribute`**: Set to `True` to use `align` instead of an appropriate `style` attribute
+
+ Default: `'False'`
+
A trivial example:
```python
markdown.markdown(some_text, extensions=['tables'])
```
+
+### Examples
+
+For an example, let us suppose that alignment should be controlled by the legacy `align`
+attribute.
+
+```pycon
+>>> from markdown.extensions.tables import TableExtension
+>>> html = markdown.markdown(text,
+... extensions=[TableExtension(use_align_attribute=True)]
+... )
+```
* **`title`**:
Title to insert in the Table of Contents' `<div>`. Defaults to `None`.
+* **`title_class`**:
+ CSS class used for the title contained in the Table of Contents. Defaults to `toctitle`.
+
+* **`toc_class`**:
+ CSS class(es) used for the `<div>` containing the Table of Contents. Defaults to `toc`.
+
* **`anchorlink`**:
Set to `True` to cause all headers to link to themselves. Default is `False`.
* **`permalink_title`**:
Title attribute of the permanent link. Defaults to `Permanent link`.
+* **`permalink_leading`**:
+ Set to `True` if the extension should generate leading permanent links.
+ Default is `False`.
+
+ Leading permanent links are placed at the start of the header tag,
+ before any header content. The default `permalink` behavior (when
+ `permalink_leading` is unset or set to `False`) creates trailing
+ permanent links, which are placed at the end of the header content.
+
* **`baselevel`**:
Base level for headers. Defaults to `1`.
* **`slugify`**:
Callable to generate anchors.
- Default: `markdown.extensions.headerid.slugify`
+ Default: `markdown.extensions.toc.slugify`
In order to use a different algorithm to define the id attributes, define and
pass in a callable which takes the following two arguments:
The callable must return a string appropriate for use in HTML `id` attributes.
An alternate version of the default callable supporting Unicode strings is also
- provided as `markdown.extensions.headerid.slugify_unicode`.
+ provided as `markdown.extensions.toc.slugify_unicode`.
* **`separator`**:
Word separator. Character which replaces white space in id. Defaults to "`-`".
* Maintain a Python library (with an optional CLI wrapper) suited to use in web
server environments (never raise an exception, never write to stdout, etc.) as
an implementation of the markdown parser that follows the
- [syntax rules](https://daringfireball.net/projects/markdown/syntax) and the
- behavior of the original (markdown.pl) implementation as reasonably as
- possible (see [differences](#differences) for a few exceptions).
+ [syntax rules][] and the behavior of the original (markdown.pl)
+ implementation as reasonably as possible (see [differences](#differences) for
+ a few exceptions).
* Provide an [Extension API](extensions/api.md) which makes it possible
to change and/or extend the behavior of the parser.
+!!! Note
+
+ *This is not a CommonMark implementation*; nor is it trying to be!
+ Python-Markdown was developed long before the CommonMark specification was
+ released and has always (mostly) followed the [syntax rules][] and behavior
+ of the original reference implementation. No accommodations have been made
+ to address the changes which CommonMark has suggested. It is recommended
+ that you look elsewhere if you want an implementation which follows the
+ CommonMark specification.
+
Features
--------
In the event that one would prefer different behavior,
[tab_length](reference.md#tab_length) can be set to whatever length is
desired. Be warned however, as this will affect indentation for all aspects
- of the syntax (including root level code blocks). Alternatively, a
+ of the syntax (including root level code blocks). Alternatively, a
[third party extension] may offer a solution that meets your needs.
* __Consecutive Lists__
You may report bugs, ask for help, and discuss various other issues on the [bug tracker][].
[third party extension]: https://github.com/Python-Markdown/markdown/wiki/Third-Party-Extensions
+[syntax rules]: https://daringfireball.net/projects/markdown/syntax
[bug tracker]: https://github.com/Python-Markdown/markdown/issues
--- /dev/null
+/* Indentation. */
+div.doc-contents:not(.first) {
+ padding-left: 25px;
+}
+
+/* Mark external links as such. */
+a.external::after,
+a.autorefs-external::after {
+ /* https://primer.style/octicons/arrow-up-right-24 */
+ mask-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M18.25 15.5a.75.75 0 00.75-.75v-9a.75.75 0 00-.75-.75h-9a.75.75 0 000 1.5h7.19L6.22 16.72a.75.75 0 101.06 1.06L17.5 7.56v7.19c0 .414.336.75.75.75z"></path></svg>');
+ -webkit-mask-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M18.25 15.5a.75.75 0 00.75-.75v-9a.75.75 0 00-.75-.75h-9a.75.75 0 000 1.5h7.19L6.22 16.72a.75.75 0 101.06 1.06L17.5 7.56v7.19c0 .414.336.75.75.75z"></path></svg>');
+ content: ' ';
+
+ display: inline-block;
+ vertical-align: middle;
+ position: relative;
+
+ height: 1em;
+ width: 1em;
+ background-color: #005b81;
+}
+
+a.external:hover::after,
+a.autorefs-external:hover::after {
+ background-color: #e32e00;
+}
+
+/* Customize custom links. */
+a.autorefs code {
+ background-color: #ecf0f3;
+ font-weight: normal;
+ color: #005B81;
+}
+
+a.autorefs:hover code {
+ color: #E32E00;
+}
+
+/* Customize labels. */
+.doc-label {
+ border-radius: 15px;
+ padding: 2px 8px;
+ background-color: #f2f2f3;
+ text-wrap: nowrap;
+}
+
+.doc-label code {
+ color: #444;
+}
+
+.doc-label-deprecated {
+ background-color: #ffe4e4;
+ border: 1px solid #f66;
+}
+
+/* No shadows in any code. */
+
+code {
+ text-shadow: none;
+}
+
+/* Code spans in tables. */
+
+table code {
+ background-color: transparent !important;
+}
+
+/* Style source links */
+a.doc-source-link {
+ position: relative;
+ float: right;
+ border: 1px #005B81 solid;
+ margin: 0 5px;
+ padding: 0 5px;
+ font-weight: normal;
+ text-shadow: none;
+ background-color: #f2f2f3;
+ font-size: 1rem;
+}
+
+a.doc-source-link:hover {
+ text-decoration: none;
+ border-color: #E32E00;
+}
+
+/* Customize symbol names. */
+code.doc-symbol-attribute::after {
+ content: "Attr";
+}
+
+code.doc-symbol-function::after {
+ content: "Func";
+}
+
+code.doc-symbol-method::after {
+ content: "Method";
+}
+
+code.doc-symbol-class::after {
+ content: "Class";
+}
+
+code.doc-symbol-module::after {
+ content: "Module";
+}
Supported formats are:
* `"xhtml"`: Outputs XHTML style tags. **Default**.
- * `"html5"`: Outputs HTML style tags.
+ * `"html"`: Outputs HTML style tags.
The values can be in either lowercase or uppercase.
--- /dev/null
+{% extends "_base/attribute.html" %}
+
+{% block heading scoped %}
+ <a class="doc-source-link" href="{{ config.source.repo }}/tree/{{ config.source.tag }}/{{ attribute.filepath }}#L{{ attribute.lineno }}{% if attribute.endlineno > attribute.lineno %}-L{{ attribute.endlineno }}{% endif %}" title='View source code on GitHub'>‹›</a>
+ {%+ filter highlight(language="python", inline=True) %}
+ {{ attribute_name }}{% if attribute.annotation %}: {{ attribute.annotation }}{% endif %}
+ {% endfilter %}
+{% endblock heading %}
+
+{% block contents scoped %}
+ {{ super() }}
+ {% if attribute.value %}
+ <p>Defined Value:</p>
+ {%+ filter highlight(language="python", inline=False) %}
+{{ attribute.source }}
+ {% endfilter %}
+ {% endif %}
+{% endblock contents %}
--- /dev/null
+{% extends "_base/class.html" %}
+
+{% block heading scoped %}
+ <a class="doc-source-link" href="{{ config.source.repo }}/tree/{{ config.source.tag }}/{{ class.filepath }}#L{{ class.lineno }}" title="{{ config.source.title }}">‹›</a>
+ {{ super() }}
+{% endblock heading %}
--- /dev/null
+{{ log.debug("Rendering admonition") }}
+<div class="admonition {{ section.value.kind }}">
+ <p class="admonition-title">{{ section.title|convert_markdown(heading_level, html_id, strip_paragraph=True) }}</p>
+ {{ section.value.contents|convert_markdown(heading_level, html_id) }}
+</div>
--- /dev/null
+{% extends "_base/function.html" %}
+
+{% block heading scoped %}
+ <a class="doc-source-link" href="{{ config.source.repo }}/tree/{{ config.source.tag }}/{{ function.filepath }}#L{{ function.lineno }}{% if function.endlineno > function.lineno %}-L{{ function.endlineno }}{% endif %}" title="{{ config.source.title }}">‹›</a>
+ {{ super() }}
+{% endblock heading %}
--- /dev/null
+{% extends "_base/module.html" %}
+
+{% block heading scoped %}
+ <a class="doc-source-link" href="{{ config.source.repo }}/tree/{{ config.source.tag }}/{{ module.filepath }}" title="{{ config.source.title }}">‹›</a>
+ {{ super() }}
+{% endblock heading %}
The test tools include two different `unittest.TestCase` subclasses:
`markdown.test_tools.TestCase` and `markdown.test_tools.LegacyTestCase`.
-## markdown.test_tools.TestCase
+## `markdown.test_tools.TestCase`
The `markdown.test_tools.TestCase` class is a `unittest.TestCase` subclass with
a few additional helpers to make testing Markdown output easier.
)
```
-## markdown.test_tools.LegacyTestCase
+## `markdown.test_tools.LegacyTestCase`
In the past Python-Markdown exclusively used file-based tests. Many of those
tests still exist in Python-Markdown's test suite, including the test files from
@echo ' install Install Python-Markdown locally'
@echo ' deploy Register and upload a new release to PyPI'
@echo ' build Build a source distribution'
- @echo ' build-win Build a Windows exe distribution'
@echo ' docs Build documentation'
@echo ' test Run all tests'
@echo ' clean Clean up the source directories'
.PHONY : install
install:
- python setup.py install
+ pip install .
.PHONY : deploy
deploy:
rm -rf build
rm -rf dist
- python setup.py bdist_wheel sdist --formats gztar
+ python -m build
twine upload dist/*
.PHONY : build
build:
rm -rf build
rm -rf dist
- python setup.py bdist_wheel sdist --formats gztar
-
-.PHONY : build-win
-build-win:
- python setup.py bdist_wininst
+ python -m build
.PHONY : docs
docs:
-"""
-Python Markdown
+# Python Markdown
-A Python implementation of John Gruber's Markdown.
+# A Python implementation of John Gruber's Markdown.
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# - Documentation: https://python-markdown.github.io/
+# - GitHub: https://github.com/Python-Markdown/markdown/
+# - PyPI: https://pypi.org/project/Markdown/
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# - Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# - Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# - Copyright 2004 Manfred Stienstra (the original version)
-License: BSD (see LICENSE.md for details).
-"""
+# License: BSD (see LICENSE.md for details).
-import sys
+"""
+Python-Markdown provides two public functions ([`markdown.markdown`][] and [`markdown.markdownFromFile`][])
+both of which wrap the public class [`markdown.Markdown`][]. All submodules support these public functions
+and class and/or provide extension support.
+
+Modules:
+ core: Core functionality.
+ preprocessors: Pre-processors.
+ blockparser: Core Markdown block parser.
+ blockprocessors: Block processors.
+ treeprocessors: Tree processors.
+ inlinepatterns: Inline patterns.
+ postprocessors: Post-processors.
+ serializers: Serializers.
+ util: Utility functions.
+ htmlparser: HTML parser.
+ test_tools: Testing utilities.
+ extensions: Markdown extensions.
+"""
-# TODO: Remove this check at some point in the future.
-# (also remove flake8's 'ignore E402' comments below)
-if sys.version_info[0] < 3: # pragma: no cover
- raise ImportError('A recent version of Python 3 is required.')
+from __future__ import annotations
-from .core import Markdown, markdown, markdownFromFile # noqa: E402
-from .util import PY37 # noqa: E402
-from .pep562 import Pep562 # noqa: E402
-from .__meta__ import __version__, __version_info__ # noqa: E402
-import warnings # noqa: E402
+from .core import Markdown, markdown, markdownFromFile
+from .__meta__ import __version__, __version_info__ # noqa
# For backward compatibility as some extensions expect it...
from .extensions import Extension # noqa
__all__ = ['Markdown', 'markdown', 'markdownFromFile']
-
-__deprecated__ = {
- "version": ("__version__", __version__),
- "version_info": ("__version_info__", __version_info__)
-}
-
-
-def __getattr__(name):
- """Get attribute."""
-
- deprecated = __deprecated__.get(name)
- if deprecated:
- warnings.warn(
- "'{}' is deprecated. Use '{}' instead.".format(name, deprecated[0]),
- category=DeprecationWarning,
- stacklevel=(3 if PY37 else 4)
- )
- return deprecated[1]
- raise AttributeError("module '{}' has no attribute '{}'".format(__name__, name))
-
-
-if not PY37:
- Pep562(__name__)
-"""
-Python Markdown
+# Python Markdown
-A Python implementation of John Gruber's Markdown.
+# A Python implementation of John Gruber's Markdown.
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
-License: BSD (see LICENSE.md for details).
-"""
+# License: BSD (see LICENSE.md for details).
+
+from __future__ import annotations
import sys
import optparse
if __name__ == '__main__': # pragma: no cover
- # Support running module as a commandline command.
- # `python -m markdown [options] [args]`.
+ # Support running module as a command line command.
+ # python -m markdown [options] [args]
run()
-"""
-Python Markdown
+# Python Markdown
-A Python implementation of John Gruber's Markdown.
+# A Python implementation of John Gruber's Markdown.
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
-License: BSD (see LICENSE.md for details).
-"""
+# License: BSD (see LICENSE.md for details).
# __version_info__ format:
-# (major, minor, patch, dev/alpha/beta/rc/final, #)
-# (1, 1, 2, 'dev', 0) => "1.1.2.dev0"
-# (1, 1, 2, 'alpha', 1) => "1.1.2a1"
-# (1, 2, 0, 'beta', 2) => "1.2b2"
-# (1, 2, 0, 'rc', 4) => "1.2rc4"
-# (1, 2, 0, 'final', 0) => "1.2"
-__version_info__ = (3, 3, 7, 'final', 0)
+# (major, minor, patch, dev/alpha/beta/rc/final, #)
+# (1, 1, 2, 'dev', 0) => "1.1.2.dev0"
+# (1, 1, 2, 'alpha', 1) => "1.1.2a1"
+# (1, 2, 0, 'beta', 2) => "1.2b2"
+# (1, 2, 0, 'rc', 4) => "1.2rc4"
+# (1, 2, 0, 'final', 0) => "1.2"
+
+from __future__ import annotations
+
+
+__version_info__ = (3, 5, 1, 'final', 0)
def _get_version(version_info):
- " Returns a PEP 440-compliant version number from version_info. "
+ " Returns a PEP 440-compliant version number from `version_info`. "
assert len(version_info) == 5
assert version_info[3] in ('dev', 'alpha', 'beta', 'rc', 'final')
-"""
-Python Markdown
+# Python Markdown
+
+# A Python implementation of John Gruber's Markdown.
-A Python implementation of John Gruber's Markdown.
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# License: BSD (see LICENSE.md for details).
+
+"""
+The block parser handles basic parsing of Markdown blocks. It doesn't concern
+itself with inline elements such as `**bold**` or `*italics*`, but rather just
+catches blocks, lists, quotes, etc.
-License: BSD (see LICENSE.md for details).
+The `BlockParser` is made up of a bunch of `BlockProcessors`, each handling a
+different type of block. Extensions may add/replace/remove `BlockProcessors`
+as they need to alter how Markdown blocks are parsed.
"""
+from __future__ import annotations
+
import xml.etree.ElementTree as etree
+from typing import TYPE_CHECKING, Iterable, Any
from . import util
+if TYPE_CHECKING: # pragma: no cover
+ from markdown import Markdown
+ from .blockprocessors import BlockProcessor
+
class State(list):
""" Track the current and nested state of the parser.
- This utility class is used to track the state of the BlockParser and
+ This utility class is used to track the state of the `BlockParser` and
support multiple levels if nesting. It's just a simple API wrapped around
a list. Each time a state is set, that state is appended to the end of the
list. Each time a state is reset, that state is removed from the end of
"""
- def set(self, state):
+ def set(self, state: Any):
""" Set a new state. """
self.append(state)
- def reset(self):
+ def reset(self) -> None:
""" Step back one step in nested state. """
self.pop()
- def isstate(self, state):
+ def isstate(self, state: Any) -> bool:
""" Test that top (current) level is of given state. """
if len(self):
return self[-1] == state
class BlockParser:
- """ Parse Markdown blocks into an ElementTree object.
+ """ Parse Markdown blocks into an `ElementTree` object.
+
+ A wrapper class that stitches the various `BlockProcessors` together,
+ looping through them and creating an `ElementTree` object.
- A wrapper class that stitches the various BlockProcessors together,
- looping through them and creating an ElementTree object.
"""
- def __init__(self, md):
- self.blockprocessors = util.Registry()
+ def __init__(self, md: Markdown):
+ """ Initialize the block parser.
+
+ Arguments:
+ md: A Markdown instance.
+
+ Attributes:
+ BlockParser.md (Markdown): A Markdown instance.
+ BlockParser.state (State): Tracks the nesting level of current location in document being parsed.
+ BlockParser.blockprocessors (util.Registry): A collection of
+ [`blockprocessors`][markdown.blockprocessors].
+
+ """
+ self.blockprocessors: util.Registry[BlockProcessor] = util.Registry()
self.state = State()
self.md = md
- @property
- @util.deprecated("Use 'md' instead.")
- def markdown(self):
- # TODO: remove this later
- return self.md
-
- def parseDocument(self, lines):
- """ Parse a markdown document into an ElementTree.
+ def parseDocument(self, lines: Iterable[str]) -> etree.ElementTree:
+ """ Parse a Markdown document into an `ElementTree`.
- Given a list of lines, an ElementTree object (not just a parent
- Element) is created and the root element is passed to the parser
- as the parent. The ElementTree object is returned.
+ Given a list of lines, an `ElementTree` object (not just a parent
+ `Element`) is created and the root element is passed to the parser
+ as the parent. The `ElementTree` object is returned.
This should only be called on an entire document, not pieces.
+ Arguments:
+ lines: A list of lines (strings).
+
+ Returns:
+ An element tree.
"""
- # Create a ElementTree from the lines
+ # Create an `ElementTree` from the lines
self.root = etree.Element(self.md.doc_tag)
self.parseChunk(self.root, '\n'.join(lines))
return etree.ElementTree(self.root)
- def parseChunk(self, parent, text):
- """ Parse a chunk of markdown text and attach to given etree node.
+ def parseChunk(self, parent: etree.Element, text: str) -> None:
+ """ Parse a chunk of Markdown text and attach to given `etree` node.
- While the ``text`` argument is generally assumed to contain multiple
+ While the `text` argument is generally assumed to contain multiple
blocks which will be split on blank lines, it could contain only one
block. Generally, this method would be called by extensions when
block parsing is required.
- The ``parent`` etree Element passed in is altered in place.
+ The `parent` `etree` Element passed in is altered in place.
Nothing is returned.
+ Arguments:
+ parent: The parent element.
+ text: The text to parse.
+
"""
self.parseBlocks(parent, text.split('\n\n'))
- def parseBlocks(self, parent, blocks):
- """ Process blocks of markdown text and attach to given etree node.
+ def parseBlocks(self, parent: etree.Element, blocks: list[str]) -> None:
+ """ Process blocks of Markdown text and attach to given `etree` node.
- Given a list of ``blocks``, each blockprocessor is stepped through
+ Given a list of `blocks`, each `blockprocessor` is stepped through
until there are no blocks left. While an extension could potentially
call this method directly, it's generally expected to be used
internally.
This is a public method as an extension may need to add/alter
- additional BlockProcessors which call this method to recursively
+ additional `BlockProcessors` which call this method to recursively
parse a nested block.
+ Arguments:
+ parent: The parent element.
+ blocks: The blocks of text to parse.
+
"""
while blocks:
for processor in self.blockprocessors:
-"""
-Python Markdown
-
-A Python implementation of John Gruber's Markdown.
+# Python Markdown
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# A Python implementation of John Gruber's Markdown.
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-License: BSD (see LICENSE.md for details).
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
-CORE MARKDOWN BLOCKPARSER
-===========================================================================
+# License: BSD (see LICENSE.md for details).
-This parser handles basic parsing of Markdown blocks. It doesn't concern
-itself with inline elements such as **bold** or *italics*, but rather just
-catches blocks, lists, quotes, etc.
-
-The BlockParser is made up of a bunch of BlockProcessors, each handling a
-different type of block. Extensions may add/replace/remove BlockProcessors
-as they need to alter how markdown blocks are parsed.
+"""
+A block processor parses blocks of text and adds new elements to the ElementTree. Blocks of text,
+separated from other text by blank lines, may have a different syntax and produce a differently
+structured tree than other Markdown. Block processors excel at handling code formatting, equation
+layouts, tables, etc.
"""
+from __future__ import annotations
+
import logging
import re
import xml.etree.ElementTree as etree
+from typing import TYPE_CHECKING, Any
from . import util
from .blockparser import BlockParser
+if TYPE_CHECKING: # pragma: no cover
+ from markdown import Markdown
+
logger = logging.getLogger('MARKDOWN')
-def build_block_parser(md, **kwargs):
+def build_block_parser(md: Markdown, **kwargs: Any) -> BlockParser:
""" Build the default block parser used by Markdown. """
parser = BlockParser(md)
parser.blockprocessors.register(EmptyBlockProcessor(parser), 'empty', 100)
""" Base class for block processors.
Each subclass will provide the methods below to work with the source and
- tree. Each processor will need to define it's own ``test`` and ``run``
- methods. The ``test`` method should return True or False, to indicate
+ tree. Each processor will need to define it's own `test` and `run`
+ methods. The `test` method should return True or False, to indicate
whether the current block should be processed by this processor. If the
- test passes, the parser will call the processors ``run`` method.
+ test passes, the parser will call the processors `run` method.
+
+ Attributes:
+ BlockProcessor.parser (BlockParser): The `BlockParser` instance this is attached to.
+ BlockProcessor.tab_length (int): The tab length set on the `Markdown` instance.
"""
- def __init__(self, parser):
+ def __init__(self, parser: BlockParser):
self.parser = parser
self.tab_length = parser.md.tab_length
- def lastChild(self, parent):
- """ Return the last child of an etree element. """
+ def lastChild(self, parent: etree.Element) -> etree.Element | None:
+ """ Return the last child of an `etree` element. """
if len(parent):
return parent[-1]
else:
return None
- def detab(self, text, length=None):
+ def detab(self, text: str, length: int | None = None) -> tuple[str, str]:
""" Remove a tab from the front of each line of the given text. """
if length is None:
length = self.tab_length
break
return '\n'.join(newtext), '\n'.join(lines[len(newtext):])
- def looseDetab(self, text, level=1):
+ def looseDetab(self, text: str, level: int = 1) -> str:
""" Remove a tab from front of lines but allowing dedented lines. """
lines = text.split('\n')
for i in range(len(lines)):
lines[i] = lines[i][self.tab_length*level:]
return '\n'.join(lines)
- def test(self, parent, block):
+ def test(self, parent: etree.Element, block: str) -> bool:
""" Test for block type. Must be overridden by subclasses.
- As the parser loops through processors, it will call the ``test``
+ As the parser loops through processors, it will call the `test`
method on each to determine if the given block of text is of that
- type. This method must return a boolean ``True`` or ``False``. The
+ type. This method must return a boolean `True` or `False`. The
actual method of testing is left to the needs of that particular
- block type. It could be as simple as ``block.startswith(some_string)``
+ block type. It could be as simple as `block.startswith(some_string)`
or a complex regular expression. As the block type may be different
depending on the parent of the block (i.e. inside a list), the parent
- etree element is also provided and may be used as part of the test.
+ `etree` element is also provided and may be used as part of the test.
- Keywords:
-
- * ``parent``: A etree element which will be the parent of the block.
- * ``block``: A block of text from the source which has been split at
- blank lines.
+ Keyword arguments:
+ parent: An `etree` element which will be the parent of the block.
+ block: A block of text from the source which has been split at blank lines.
"""
pass # pragma: no cover
- def run(self, parent, blocks):
+ def run(self, parent: etree.Element, blocks: list[str]) -> bool | None:
""" Run processor. Must be overridden by subclasses.
When the parser determines the appropriate type of a block, the parser
- will call the corresponding processor's ``run`` method. This method
+ will call the corresponding processor's `run` method. This method
should parse the individual lines of the block and append them to
- the etree.
+ the `etree`.
- Note that both the ``parent`` and ``etree`` keywords are pointers
+ Note that both the `parent` and `etree` keywords are pointers
to instances of the objects which should be edited in place. Each
processor must make changes to the existing objects as there is no
mechanism to return new/different objects to replace them.
- This means that this method should be adding SubElements or adding text
- to the parent, and should remove (``pop``) or add (``insert``) items to
+ This means that this method should be adding `SubElements` or adding text
+ to the parent, and should remove (`pop`) or add (`insert`) items to
the list of blocks.
- Keywords:
+ If `False` is returned, this will have the same effect as returning `False`
+ from the `test` method.
- * ``parent``: A etree element which is the parent of the current block.
- * ``blocks``: A list of all remaining blocks of the document.
+ Keyword arguments:
+ parent: An `etree` element which is the parent of the current block.
+ blocks: A list of all remaining blocks of the document.
"""
pass # pragma: no cover
class ListIndentProcessor(BlockProcessor):
""" Process children of list items.
- Example:
+ Example
+
* a list item
process this part
"""
ITEM_TYPES = ['li']
+ """ List of tags used for list items. """
LIST_TYPES = ['ul', 'ol']
+ """ Types of lists this processor can operate on. """
def __init__(self, *args):
super().__init__(*args)
self.parser.state.set('detabbed')
if parent.tag in self.ITEM_TYPES:
- # It's possible that this parent has a 'ul' or 'ol' child list
+ # It's possible that this parent has a `ul` or `ol` child list
# with a member. If that is the case, then that should be the
# parent. This is intended to catch the edge case of an indented
# list whose first member was parsed previous to this point
- # see OListProcessor
+ # see `OListProcessor`
if len(parent) and parent[-1].tag in self.LIST_TYPES:
self.parser.parseBlocks(parent[-1], [block])
else:
- # The parent is already a li. Just parse the child block.
+ # The parent is already a `li`. Just parse the child block.
self.parser.parseBlocks(parent, [block])
elif sibling.tag in self.ITEM_TYPES:
- # The sibling is a li. Use it as parent.
+ # The sibling is a `li`. Use it as parent.
self.parser.parseBlocks(sibling, [block])
elif len(sibling) and sibling[-1].tag in self.ITEM_TYPES:
- # The parent is a list (``ol`` or ``ul``) which has children.
- # Assume the last child li is the parent of this block.
+ # The parent is a list (`ol` or `ul`) which has children.
+ # Assume the last child `li` is the parent of this block.
if sibling[-1].text:
- # If the parent li has text, that text needs to be moved to a p
- # The p must be 'inserted' at beginning of list in the event
- # that other children already exist i.e.; a nested sublist.
+ # If the parent `li` has text, that text needs to be moved to a `p`
+ # The `p` must be 'inserted' at beginning of list in the event
+ # that other children already exist i.e.; a nested sub-list.
p = etree.Element('p')
p.text = sibling[-1].text
sibling[-1].text = ''
self.create_item(sibling, block)
self.parser.state.reset()
- def create_item(self, parent, block):
- """ Create a new li and parse the block with it as the parent. """
+ def create_item(self, parent: etree.Element, block: str) -> None:
+ """ Create a new `li` and parse the block with it as the parent. """
li = etree.SubElement(parent, 'li')
self.parser.parseBlocks(li, [block])
- def get_level(self, parent, block):
- """ Get level of indent based on list level. """
+ def get_level(self, parent: etree.Element, block: str) -> tuple[int, etree.Element]:
+ """ Get level of indentation based on list level. """
# Get indent level
m = self.INDENT_RE.match(block)
if m:
else:
indent_level = 0
if self.parser.state.isstate('list'):
- # We're in a tightlist - so we already are at correct parent.
+ # We're in a tight-list - so we already are at correct parent.
level = 1
else:
- # We're in a looselist - so we need to find parent.
+ # We're in a loose-list - so we need to find parent.
level = 0
# Step through children of tree to find matching indent level.
while indent_level > level:
level += 1
parent = child
else:
- # No more child levels. If we're short of indent_level,
+ # No more child levels. If we're short of `indent_level`,
# we have a code block. So we stop here.
break
return level, parent
len(sibling) and sibling[0].tag == "code"):
# The previous block was a code block. As blank lines do not start
# new code blocks, append this block to the previous, adding back
- # linebreaks removed from the split into a list.
+ # line breaks removed from the split into a list.
code = sibling[0]
block, theRest = self.detab(block)
code.text = util.AtomicString(
'{}\n{}\n'.format(code.text, util.code_escape(block.rstrip()))
)
else:
- # This is a new codeblock. Create the elements and insert text.
+ # This is a new code block. Create the elements and insert text.
pre = etree.SubElement(parent, 'pre')
code = etree.SubElement(pre, 'code')
block, theRest = self.detab(block)
class BlockQuoteProcessor(BlockProcessor):
+ """ Process blockquotes. """
RE = re.compile(r'(^|\n)[ ]{0,3}>[ ]?(.*)')
before = block[:m.start()] # Lines before blockquote
# Pass lines before blockquote in recursively for parsing first.
self.parser.parseBlocks(parent, [before])
- # Remove ``> `` from beginning of each line.
+ # Remove `> ` from beginning of each line.
block = '\n'.join(
[self.clean(line) for line in block[m.start():].split('\n')]
)
# This is a new blockquote. Create a new parent element.
quote = etree.SubElement(parent, 'blockquote')
# Recursively parse block with blockquote as parent.
- # change parser state so blockquotes embedded in lists use p tags
+ # change parser state so blockquotes embedded in lists use `p` tags
self.parser.state.set('blockquote')
self.parser.parseChunk(quote, block)
self.parser.state.reset()
- def clean(self, line):
- """ Remove ``>`` from beginning of a line. """
+ def clean(self, line: str) -> str:
+ """ Remove `>` from beginning of a line. """
m = self.RE.match(line)
if line.strip() == ">":
return ""
class OListProcessor(BlockProcessor):
""" Process ordered list blocks. """
- TAG = 'ol'
- # The integer (python string) with which the lists starts (default=1)
- # Eg: If list is initialized as)
- # 3. Item
- # The ol tag will get starts="3" attribute
- STARTSWITH = '1'
- # Lazy ol - ignore startswith
- LAZY_OL = True
- # List of allowed sibling tags.
- SIBLING_TAGS = ['ol', 'ul']
-
- def __init__(self, parser):
+ TAG: str = 'ol'
+ """ The tag used for the the wrapping element. """
+ STARTSWITH: str = '1'
+ """
+ The integer (as a string ) with which the list starts. For example, if a list is initialized as
+ `3. Item`, then the `ol` tag will be assigned an HTML attribute of `starts="3"`. Default: `"1"`.
+ """
+ LAZY_OL: bool = True
+ """ Ignore `STARTSWITH` if `True`. """
+ SIBLING_TAGS: list[str] = ['ol', 'ul']
+ """
+ Markdown does not require the type of a new list item match the previous list item type.
+ This is the list of types which can be mixed.
+ """
+
+ def __init__(self, parser: BlockParser):
super().__init__(parser)
- # Detect an item (``1. item``). ``group(1)`` contains contents of item.
+ # Detect an item (`1. item`). `group(1)` contains contents of item.
self.RE = re.compile(r'^[ ]{0,%d}\d+\.[ ]+(.*)' % (self.tab_length - 1))
# Detect items on secondary lines. they can be of either list type.
self.CHILD_RE = re.compile(r'^[ ]{0,%d}((\d+\.)|[*+-])[ ]+(.*)' %
return bool(self.RE.match(block))
def run(self, parent, blocks):
- # Check fr multiple items in one block.
+ # Check for multiple items in one block.
items = self.get_items(blocks.pop(0))
sibling = self.lastChild(parent)
if sibling is not None and sibling.tag in self.SIBLING_TAGS:
# Previous block was a list item, so set that as parent
lst = sibling
- # make sure previous item is in a p- if the item has text,
- # then it isn't in a p
+ # make sure previous item is in a `p` - if the item has text,
+ # then it isn't in a `p`
if lst[-1].text:
# since it's possible there are other children for this
- # sibling, we can't just SubElement the p, we need to
+ # sibling, we can't just `SubElement` the `p`, we need to
# insert it as the first item.
p = etree.Element('p')
p.text = lst[-1].text
lst[-1].text = ''
lst[-1].insert(0, p)
- # if the last item has a tail, then the tail needs to be put in a p
+ # if the last item has a tail, then the tail needs to be put in a `p`
# likely only when a header is not followed by a blank line
lch = self.lastChild(lst[-1])
if lch is not None and lch.tail:
p.text = lch.tail.lstrip()
lch.tail = ''
- # parse first block differently as it gets wrapped in a p.
+ # parse first block differently as it gets wrapped in a `p`.
li = etree.SubElement(lst, 'li')
self.parser.state.set('looselist')
firstitem = items.pop(0)
elif parent.tag in ['ol', 'ul']:
# this catches the edge case of a multi-item indented list whose
# first item is in a blank parent-list item:
- # * * subitem1
- # * subitem2
- # see also ListIndentProcessor
+ # * * subitem1
+ # * subitem2
+ # see also `ListIndentProcessor`
lst = parent
else:
# This is a new list so create parent with appropriate tag.
# Item is indented. Parse with last item as parent
self.parser.parseBlocks(lst[-1], [item])
else:
- # New item. Create li and parse with it as parent
+ # New item. Create `li` and parse with it as parent
li = etree.SubElement(lst, 'li')
self.parser.parseBlocks(li, [item])
self.parser.state.reset()
- def get_items(self, block):
+ def get_items(self, block: str) -> list[str]:
""" Break a block into list items. """
items = []
for line in block.split('\n'):
class UListProcessor(OListProcessor):
""" Process unordered list blocks. """
- TAG = 'ul'
+ TAG: str = 'ul'
+ """ The tag used for the the wrapping element. """
- def __init__(self, parser):
+ def __init__(self, parser: BlockParser):
super().__init__(parser)
- # Detect an item (``1. item``). ``group(1)`` contains contents of item.
+ # Detect an item (`1. item`). `group(1)` contains contents of item.
self.RE = re.compile(r'^[ ]{0,%d}[*+-][ ]+(.*)' % (self.tab_length - 1))
def run(self, parent, blocks):
lines = blocks.pop(0).split('\n')
- # Determine level. ``=`` is 1 and ``-`` is 2.
+ # Determine level. `=` is 1 and `-` is 2.
if lines[1].startswith('='):
level = 1
else:
class HRProcessor(BlockProcessor):
""" Process Horizontal Rules. """
- # Python's re module doesn't officially support atomic grouping. However you can fake it.
+ # Python's `re` module doesn't officially support atomic grouping. However you can fake it.
# See https://stackoverflow.com/a/13577411/866026
RE = r'^[ ]{0,3}(?=(?P<atomicgroup>(-+[ ]{0,2}){3,}|(_+[ ]{0,2}){3,}|(\*+[ ]{0,2}){3,}))(?P=atomicgroup)[ ]*$'
# Detect hr on any line of a block.
def run(self, parent, blocks):
block = blocks.pop(0)
match = self.match
- # Check for lines in block before hr.
+ # Check for lines in block before `hr`.
prelines = block[:match.start()].rstrip('\n')
if prelines:
- # Recursively parse lines before hr so they get parsed first.
+ # Recursively parse lines before `hr` so they get parsed first.
self.parser.parseBlocks(parent, [prelines])
# create hr
etree.SubElement(parent, 'hr')
- # check for lines in block after hr.
+ # check for lines in block after `hr`.
postlines = block[match.end():].lstrip('\n')
if postlines:
- # Add lines after hr to master blocks for later parsing.
+ # Add lines after `hr` to master blocks for later parsing.
blocks.insert(0, postlines)
sibling = self.lastChild(parent)
if (sibling is not None and sibling.tag == 'pre' and
len(sibling) and sibling[0].tag == 'code'):
- # Last block is a codeblock. Append to preserve whitespace.
+ # Last block is a code block. Append to preserve whitespace.
sibling[0].text = util.AtomicString(
'{}{}'.format(sibling[0].text, filler)
)
# Line 2 of list item - not part of header.
sibling = self.lastChild(parent)
if sibling is not None:
- # Insetrt after sibling.
+ # Insert after sibling.
if sibling.tail:
sibling.tail = '{}\n{}'.format(sibling.tail, block)
else:
-"""
-Python Markdown
+# Python Markdown
-A Python implementation of John Gruber's Markdown.
+# A Python implementation of John Gruber's Markdown.
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
-License: BSD (see LICENSE.md for details).
-"""
+# License: BSD (see LICENSE.md for details).
+
+from __future__ import annotations
import codecs
import sys
import logging
import importlib
+from typing import TYPE_CHECKING, Any, Callable, ClassVar, Mapping, Sequence, TextIO
from . import util
from .preprocessors import build_preprocessors
from .blockprocessors import build_block_parser
from .postprocessors import build_postprocessors
from .extensions import Extension
from .serializers import to_html_string, to_xhtml_string
+from .util import BLOCK_LEVEL_ELEMENTS
+
+if TYPE_CHECKING: # pragma: no cover
+ from xml.etree.ElementTree import Element
__all__ = ['Markdown', 'markdown', 'markdownFromFile']
class Markdown:
- """Convert Markdown to HTML."""
+ """
+ A parser which converts Markdown to HTML.
+
+ Attributes:
+ Markdown.tab_length (int): The number of spaces which correspond to a single tab. Default: `4`.
+ Markdown.ESCAPED_CHARS (list[str]): List of characters which get the backslash escape treatment.
+ Markdown.block_level_elements (list[str]): List of HTML tags which get treated as block-level elements.
+ See [`markdown.util.BLOCK_LEVEL_ELEMENTS`][] for the full list of elements.
+ Markdown.registeredExtensions (list[Extension]): List of extensions which have called
+ [`registerExtension`][markdown.Markdown.registerExtension] during setup.
+ Markdown.doc_tag (str): Element used to wrap document. Default: `div`.
+ Markdown.stripTopLevelTags (bool): Indicates whether the `doc_tag` should be removed. Default: 'True'.
+ Markdown.references (dict[str, tuple[str, str]]): A mapping of link references found in a parsed document
+ where the key is the reference name and the value is a tuple of the URL and title.
+ Markdown.htmlStash (util.HtmlStash): The instance of the `HtmlStash` used by an instance of this class.
+ Markdown.output_formats (dict[str, Callable[xml.etree.ElementTree.Element]]): A mapping of known output
+ formats by name and their respective serializers. Each serializer must be a callable which accepts an
+ [`Element`][xml.etree.ElementTree.Element] and returns a `str`.
+ Markdown.output_format (str): The output format set by
+ [`set_output_format`][markdown.Markdown.set_output_format].
+ Markdown.serializer (Callable[xml.etree.ElementTree.Element]): The serializer set by
+ [`set_output_format`][markdown.Markdown.set_output_format].
+ Markdown.preprocessors (util.Registry): A collection of [`preprocessors`][markdown.preprocessors].
+ Markdown.parser (blockparser.BlockParser): A collection of [`blockprocessors`][markdown.blockprocessors].
+ Markdown.inlinePatterns (util.Registry): A collection of [`inlinepatterns`][markdown.inlinepatterns].
+ Markdown.treeprocessors (util.Registry): A collection of [`treeprocessors`][markdown.treeprocessors].
+ Markdown.postprocessors (util.Registry): A collection of [`postprocessors`][markdown.postprocessors].
+
+ """
doc_tag = "div" # Element used to wrap document - later removed
- output_formats = {
+ output_formats: ClassVar[dict[str, Callable[[Element], str]]] = {
'html': to_html_string,
'xhtml': to_xhtml_string,
}
+ """
+ A mapping of known output formats by name and their respective serializers. Each serializer must be a
+ callable which accepts an [`Element`][xml.etree.ElementTree.Element] and returns a `str`.
+ """
def __init__(self, **kwargs):
"""
Creates a new Markdown instance.
- Keyword arguments:
+ Keyword Arguments:
+ extensions (list[Extension | str]): A list of extensions.
- * extensions: A list of extensions.
- If an item is an instance of a subclass of `markdown.extension.Extension`, the instance will be used
- as-is. If an item is of type string, first an entry point will be loaded. If that fails, the string is
- assumed to use Python dot notation (`path.to.module:ClassName`) to load a markdown.Extension subclass. If
- no class is specified, then a `makeExtension` function is called within the specified module.
- * extension_configs: Configuration settings for extensions.
- * output_format: Format of output. Supported formats are:
- * "xhtml": Outputs XHTML style tags. Default.
- * "html": Outputs HTML style tags.
- * tab_length: Length of tabs in the source. Default: 4
+ If an item is an instance of a subclass of [`markdown.extensions.Extension`][],
+ the instance will be used as-is. If an item is of type `str`, it is passed
+ to [`build_extension`][markdown.Markdown.build_extension] with its corresponding
+ `extension_configs` and the returned instance of [`markdown.extensions.Extension`][]
+ is used.
+ extension_configs (dict[str, dict[str, Any]]): Configuration settings for extensions.
+ output_format (str): Format of output. Supported formats are:
+
+ * `xhtml`: Outputs XHTML style tags. Default.
+ * `html`: Outputs HTML style tags.
+ tab_length (int): Length of tabs in the source. Default: `4`
"""
- self.tab_length = kwargs.get('tab_length', 4)
-
- self.ESCAPED_CHARS = ['\\', '`', '*', '_', '{', '}', '[', ']',
- '(', ')', '>', '#', '+', '-', '.', '!']
-
- self.block_level_elements = [
- # Elements which are invalid to wrap in a `<p>` tag.
- # See https://w3c.github.io/html/grouping-content.html#the-p-element
- 'address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl',
- 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3',
- 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'main', 'menu', 'nav', 'ol',
- 'p', 'pre', 'section', 'table', 'ul',
- # Other elements which Markdown should not be mucking up the contents of.
- 'canvas', 'colgroup', 'dd', 'body', 'dt', 'group', 'iframe', 'li', 'legend',
- 'math', 'map', 'noscript', 'output', 'object', 'option', 'progress', 'script',
- 'style', 'summary', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'tr', 'video'
+ self.tab_length: int = kwargs.get('tab_length', 4)
+
+ self.ESCAPED_CHARS: list[str] = [
+ '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!'
]
+ """ List of characters which get the backslash escape treatment. """
- self.registeredExtensions = []
- self.docType = ""
- self.stripTopLevelTags = True
+ self.block_level_elements: list[str] = BLOCK_LEVEL_ELEMENTS.copy()
+
+ self.registeredExtensions: list[Extension] = []
+ self.docType = "" # TODO: Maybe delete this. It does not appear to be used anymore.
+ self.stripTopLevelTags: bool = True
self.build_parser()
- self.references = {}
- self.htmlStash = util.HtmlStash()
+ self.references: dict[str, tuple[str, str]] = {}
+ self.htmlStash: util.HtmlStash = util.HtmlStash()
self.registerExtensions(extensions=kwargs.get('extensions', []),
configs=kwargs.get('extension_configs', {}))
self.set_output_format(kwargs.get('output_format', 'xhtml'))
self.reset()
- def build_parser(self):
- """ Build the parser from the various parts. """
+ def build_parser(self) -> Markdown:
+ """
+ Build the parser from the various parts.
+
+ Assigns a value to each of the following attributes on the class instance:
+
+ * **`Markdown.preprocessors`** ([`Registry`][markdown.util.Registry]) -- A collection of
+ [`preprocessors`][markdown.preprocessors].
+ * **`Markdown.parser`** ([`BlockParser`][markdown.blockparser.BlockParser]) -- A collection of
+ [`blockprocessors`][markdown.blockprocessors].
+ * **`Markdown.inlinePatterns`** ([`Registry`][markdown.util.Registry]) -- A collection of
+ [`inlinepatterns`][markdown.inlinepatterns].
+ * **`Markdown.treeprocessors`** ([`Registry`][markdown.util.Registry]) -- A collection of
+ [`treeprocessors`][markdown.treeprocessors].
+ * **`Markdown.postprocessors`** ([`Registry`][markdown.util.Registry]) -- A collection of
+ [`postprocessors`][markdown.postprocessors].
+
+ This method could be redefined in a subclass to build a custom parser which is made up of a different
+ combination of processors and patterns.
+
+ """
self.preprocessors = build_preprocessors(self)
self.parser = build_block_parser(self)
self.inlinePatterns = build_inlinepatterns(self)
self.postprocessors = build_postprocessors(self)
return self
- def registerExtensions(self, extensions, configs):
+ def registerExtensions(
+ self,
+ extensions: Sequence[Extension | str],
+ configs: Mapping[str, Mapping[str, Any]]
+ ) -> Markdown:
"""
- Register extensions with this instance of Markdown.
+ Load a list of extensions into an instance of the `Markdown` class.
- Keyword arguments:
+ Arguments:
+ extensions (list[Extension | str]): A list of extensions.
- * extensions: A list of extensions, which can either
- be strings or objects.
- * configs: A dictionary mapping extension names to config options.
+ If an item is an instance of a subclass of [`markdown.extensions.Extension`][],
+ the instance will be used as-is. If an item is of type `str`, it is passed
+ to [`build_extension`][markdown.Markdown.build_extension] with its corresponding `configs` and the
+ returned instance of [`markdown.extensions.Extension`][] is used.
+ configs (dict[str, dict[str, Any]]): Configuration settings for extensions.
"""
for ext in extensions:
if isinstance(ext, str):
ext = self.build_extension(ext, configs.get(ext, {}))
if isinstance(ext, Extension):
- ext._extendMarkdown(self)
+ ext.extendMarkdown(self)
logger.debug(
'Successfully loaded extension "%s.%s".'
% (ext.__class__.__module__, ext.__class__.__name__)
)
return self
- def build_extension(self, ext_name, configs):
+ def build_extension(self, ext_name: str, configs: Mapping[str, Any]) -> Extension:
"""
- Build extension from a string name, then return an instance.
+ Build extension from a string name, then return an instance using the given `configs`.
+
+ Arguments:
+ ext_name: Name of extension as a string.
+ configs: Configuration settings for extension.
+
+ Returns:
+ An instance of the extension with the given configuration settings.
First attempt to load an entry point. The string name must be registered as an entry point in the
- `markdown.extensions` group which points to a subclass of the `markdown.extensions.Extension` class.
+ `markdown.extensions` group which points to a subclass of the [`markdown.extensions.Extension`][] class.
If multiple distributions have registered the same name, the first one found is returned.
If no entry point is found, assume dot notation (`path.to.module:ClassName`). Load the specified class and
return an instance. If no class is specified, import the module and call a `makeExtension` function and return
- the Extension instance returned by that function.
+ the [`markdown.extensions.Extension`][] instance returned by that function.
"""
configs = dict(configs)
- entry_points = [ep for ep in util.INSTALLED_EXTENSIONS if ep.name == ext_name]
+ entry_points = [ep for ep in util.get_installed_extensions() if ep.name == ext_name]
if entry_points:
ext = entry_points[0].load()
return ext(**configs)
# Load given class name from module.
return getattr(module, class_name)(**configs)
else:
- # Expect makeExtension() function to return a class.
+ # Expect `makeExtension()` function to return a class.
try:
return module.makeExtension(**configs)
except AttributeError as e:
e.args = (message,) + e.args[1:]
raise
- def registerExtension(self, extension):
- """ This gets called by the extension """
+ def registerExtension(self, extension: Extension) -> Markdown:
+ """
+ Register an extension as having a resettable state.
+
+ Arguments:
+ extension: An instance of the extension to register.
+
+ This should get called once by an extension during setup. A "registered" extension's
+ `reset` method is called by [`Markdown.reset()`][markdown.Markdown.reset]. Not all extensions have or need a
+ resettable state, and so it should not be assumed that all extensions are "registered."
+
+ """
self.registeredExtensions.append(extension)
return self
- def reset(self):
+ def reset(self) -> Markdown:
"""
- Resets all state variables so that we can start with a new text.
+ Resets all state variables to prepare the parser instance for new input.
+
+ Called once upon creation of a class instance. Should be called manually between calls
+ to [`Markdown.convert`][markdown.Markdown.convert].
"""
self.htmlStash.reset()
self.references.clear()
return self
- def set_output_format(self, format):
- """ Set the output format for the class instance. """
- self.output_format = format.lower().rstrip('145') # ignore num
+ def set_output_format(self, format: str) -> Markdown:
+ """
+ Set the output format for the class instance.
+
+ Arguments:
+ format: Must be a known value in `Markdown.output_formats`.
+
+ """
+ self.output_format = format.lower().rstrip('145') # ignore number
try:
self.serializer = self.output_formats[self.output_format]
except KeyError as e:
raise
return self
- def is_block_level(self, tag):
- """Check if the tag is a block level HTML tag."""
+ # Note: the `tag` argument is type annotated `Any` as ElementTree uses many various objects as tags.
+ # As there is no standardization in ElementTree, the type of a given tag is unpredictable.
+ def is_block_level(self, tag: Any) -> bool:
+ """
+ Check if the given `tag` is a block level HTML tag.
+
+ Returns `True` for any string listed in `Markdown.block_level_elements`. A `tag` which is
+ not a string always returns `False`.
+
+ """
if isinstance(tag, str):
return tag.lower().rstrip('/') in self.block_level_elements
# Some ElementTree tags are not strings, so return False.
return False
- def convert(self, source):
+ def convert(self, source: str) -> str:
"""
- Convert markdown to serialized XHTML or HTML.
+ Convert a Markdown string to a string in the specified output format.
- Keyword arguments:
+ Arguments:
+ source: Markdown formatted text as Unicode or ASCII string.
- * source: Source text as a Unicode string.
+ Returns:
+ A string in the specified output format.
- Markdown processing takes place in five steps:
+ Markdown parsing takes place in five steps:
- 1. A bunch of "preprocessors" munge the input text.
- 2. BlockParser() parses the high-level structural elements of the
- pre-processed text into an ElementTree.
- 3. A bunch of "treeprocessors" are run against the ElementTree. One
- such treeprocessor runs InlinePatterns against the ElementTree,
- detecting inline markup.
- 4. Some post-processors are run against the text after the ElementTree
- has been serialized into text.
- 5. The output is written to a string.
+ 1. A bunch of [`preprocessors`][markdown.preprocessors] munge the input text.
+ 2. A [`BlockParser`][markdown.blockparser.BlockParser] parses the high-level structural elements of the
+ pre-processed text into an [`ElementTree`][xml.etree.ElementTree.ElementTree] object.
+ 3. A bunch of [`treeprocessors`][markdown.treeprocessors] are run against the
+ [`ElementTree`][xml.etree.ElementTree.ElementTree] object. One such `treeprocessor`
+ ([`markdown.treeprocessors.InlineProcessor`][]) runs [`inlinepatterns`][markdown.inlinepatterns]
+ against the [`ElementTree`][xml.etree.ElementTree.ElementTree] object, parsing inline markup.
+ 4. Some [`postprocessors`][markdown.postprocessors] are run against the text after the
+ [`ElementTree`][xml.etree.ElementTree.ElementTree] object has been serialized into text.
+ 5. The output is returned as a string.
"""
- # Fixup the source text
+ # Fix up the source text
if not source.strip():
- return '' # a blank unicode string
+ return '' # a blank Unicode string
try:
source = str(source)
except UnicodeDecodeError as e: # pragma: no cover
- # Customise error message while maintaining original trackback
- e.reason += '. -- Note: Markdown only accepts unicode input!'
+ # Customize error message while maintaining original traceback
+ e.reason += '. -- Note: Markdown only accepts Unicode input!'
raise
# Split into lines and run the line preprocessors.
return output.strip()
- def convertFile(self, input=None, output=None, encoding=None):
- """Converts a markdown file and returns the HTML as a unicode string.
+ def convertFile(
+ self,
+ input: str | TextIO | None = None,
+ output: str | TextIO | None = None,
+ encoding: str | None = None,
+ ) -> Markdown:
+ """
+ Converts a Markdown file and returns the HTML as a Unicode string.
- Decodes the file using the provided encoding (defaults to utf-8),
- passes the file content to markdown, and outputs the html to either
+ Decodes the file using the provided encoding (defaults to `utf-8`),
+ passes the file content to markdown, and outputs the HTML to either
the provided stream or the file with provided name, using the same
- encoding as the source file. The 'xmlcharrefreplace' error handler is
- used when encoding the output.
-
- **Note:** This is the only place that decoding and encoding of unicode
- takes place in Python-Markdown. (All other code is unicode-in /
- unicode-out.)
+ encoding as the source file. The
+ [`xmlcharrefreplace`](https://docs.python.org/3/library/codecs.html#error-handlers)
+ error handler is used when encoding the output.
- Keyword arguments:
+ **Note:** This is the only place that decoding and encoding of Unicode
+ takes place in Python-Markdown. (All other code is Unicode-in /
+ Unicode-out.)
- * input: File object or path. Reads from stdin if `None`.
- * output: File object or path. Writes to stdout if `None`.
- * encoding: Encoding of input and output files. Defaults to utf-8.
+ Arguments:
+ input: File object or path. Reads from `stdin` if `None`.
+ output: File object or path. Writes to `stdout` if `None`.
+ encoding: Encoding of input and output files. Defaults to `utf-8`.
"""
EXPORTED FUNCTIONS
=============================================================================
-Those are the two functions we really mean to export: markdown() and
-markdownFromFile().
+Those are the two functions we really mean to export: `markdown()` and
+`markdownFromFile()`.
"""
-def markdown(text, **kwargs):
- """Convert a markdown string to HTML and return HTML as a unicode string.
+def markdown(text: str, **kwargs: Any) -> str:
+ """
+ Convert a markdown string to HTML and return HTML as a Unicode string.
- This is a shortcut function for `Markdown` class to cover the most
- basic use case. It initializes an instance of Markdown, loads the
+ This is a shortcut function for [`Markdown`][markdown.Markdown] class to cover the most
+ basic use case. It initializes an instance of [`Markdown`][markdown.Markdown], loads the
necessary extensions and runs the parser on the given text.
- Keyword arguments:
+ Arguments:
+ text: Markdown formatted text as Unicode or ASCII string.
- * text: Markdown formatted text as Unicode or ASCII string.
- * Any arguments accepted by the Markdown class.
+ Keyword arguments:
+ **kwargs: Any arguments accepted by the Markdown class.
- Returns: An HTML document as a string.
+ Returns:
+ A string in the specified output format.
"""
md = Markdown(**kwargs)
return md.convert(text)
-def markdownFromFile(**kwargs):
- """Read markdown code from a file and write it to a file or a stream.
+def markdownFromFile(**kwargs: Any):
+ """
+ Read Markdown text from a file and write output to a file or a stream.
- This is a shortcut function which initializes an instance of Markdown,
- and calls the convertFile method rather than convert.
+ This is a shortcut function which initializes an instance of [`Markdown`][markdown.Markdown],
+ and calls the [`convertFile`][markdown.Markdown.convertFile] method rather than
+ [`convert`][markdown.Markdown.convert].
Keyword arguments:
-
- * input: a file name or readable object.
- * output: a file name or writable object.
- * encoding: Encoding of input and output.
- * Any arguments accepted by the Markdown class.
+ input (str | TextIO): A file name or readable object.
+ output (str | TextIO): A file name or writable object.
+ encoding (str): Encoding of input and output.
+ **kwargs: Any arguments accepted by the `Markdown` class.
"""
md = Markdown(**kwargs)
-"""
-Python Markdown
+# Python Markdown
+
+# A Python implementation of John Gruber's Markdown.
-A Python implementation of John Gruber's Markdown.
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# License: BSD (see LICENSE.md for details).
-License: BSD (see LICENSE.md for details).
"""
+Markdown accepts an [`Extension`][markdown.extensions.Extension] instance for each extension. Therefore, each extension
+must to define a class that extends [`Extension`][markdown.extensions.Extension] and over-rides the
+[`extendMarkdown`][markdown.extensions.Extension.extendMarkdown] method. Within this class one can manage configuration
+options for their extension and attach the various processors and patterns which make up an extension to the
+[`Markdown`][markdown.Markdown] instance.
+"""
+
+from __future__ import annotations
-import warnings
+from typing import TYPE_CHECKING, Any, Mapping, Sequence
from ..util import parseBoolValue
+if TYPE_CHECKING: # pragma: no cover
+ from markdown import Markdown
+
class Extension:
""" Base class for extensions to subclass. """
- # Default config -- to be overridden by a subclass
- # Must be of the following format:
- # {
- # 'key': ['value', 'description']
- # }
- # Note that Extension.setConfig will raise a KeyError
- # if a default is not set here.
- config = {}
+ config: Mapping[str, list] = {}
+ """
+ Default configuration for an extension.
+
+ This attribute is to be defined in a subclass and must be of the following format:
+
+ ``` python
+ config = {
+ 'key': ['value', 'description']
+ }
+ ```
+
+ Note that [`setConfig`][markdown.extensions.Extension.setConfig] will raise a [`KeyError`][]
+ if a default is not set for each option.
+ """
def __init__(self, **kwargs):
""" Initiate Extension and set up configs. """
self.setConfigs(kwargs)
- def getConfig(self, key, default=''):
- """ Return a setting for the given key or an empty string. """
+ def getConfig(self, key: str, default: Any = '') -> Any:
+ """
+ Return a single configuration option value.
+
+ Arguments:
+ key: The configuration option name.
+ default: Default value to return if key is not set.
+
+ Returns:
+ Value of stored configuration option.
+ """
if key in self.config:
return self.config[key][0]
else:
return default
- def getConfigs(self):
- """ Return all configs settings as a dict. """
+ def getConfigs(self) -> dict[str, Any]:
+ """
+ Return all configuration options.
+
+ Returns:
+ All configuration options.
+ """
return {key: self.getConfig(key) for key in self.config.keys()}
- def getConfigInfo(self):
- """ Return all config descriptions as a list of tuples. """
+ def getConfigInfo(self) -> list[tuple[str, str]]:
+ """
+ Return descriptions of all configuration options.
+
+ Returns:
+ All descriptions of configuration options.
+ """
return [(key, self.config[key][1]) for key in self.config.keys()]
- def setConfig(self, key, value):
- """ Set a config setting for `key` with the given `value`. """
+ def setConfig(self, key: str, value: Any) -> None:
+ """
+ Set a configuration option.
+
+ If the corresponding default value set in [`config`][markdown.extensions.Extension.config]
+ is a `bool` value or `None`, then `value` is passed through
+ [`parseBoolValue`][markdown.util.parseBoolValue] before being stored.
+
+ Arguments:
+ key: Name of configuration option to set.
+ value: Value to assign to option.
+
+ Raises:
+ KeyError: If `key` is not known.
+ """
if isinstance(self.config[key][0], bool):
value = parseBoolValue(value)
if self.config[key][0] is None:
value = parseBoolValue(value, preserve_none=True)
self.config[key][0] = value
- def setConfigs(self, items):
- """ Set multiple config settings given a dict or list of tuples. """
+ def setConfigs(self, items: Mapping[str, Any] | Sequence[tuple[str, Any]]):
+ """
+ Loop through a collection of configuration options, passing each to
+ [`setConfig`][markdown.extensions.Extension.setConfig].
+
+ Arguments:
+ items: Collection of configuration options.
+
+ Raises:
+ KeyError: for any unknown key.
+ """
if hasattr(items, 'items'):
# it's a dict
items = items.items()
for key, value in items:
self.setConfig(key, value)
- def _extendMarkdown(self, *args):
- """ Private wrapper around extendMarkdown. """
- md = args[0]
- try:
- self.extendMarkdown(md)
- except TypeError as e:
- if "missing 1 required positional argument" in str(e):
- # Must be a 2.x extension. Pass in a dumby md_globals.
- self.extendMarkdown(md, {})
- warnings.warn(
- "The 'md_globals' parameter of '{}.{}.extendMarkdown' is "
- "deprecated.".format(self.__class__.__module__, self.__class__.__name__),
- category=DeprecationWarning,
- stacklevel=2
- )
- else:
- raise
-
- def extendMarkdown(self, md):
+ def extendMarkdown(self, md: Markdown) -> None:
"""
Add the various processors and patterns to the Markdown Instance.
This method must be overridden by every extension.
- Keyword arguments:
-
- * md: The Markdown instance.
-
- * md_globals: Global variables in the markdown module namespace.
+ Arguments:
+ md: The Markdown instance.
"""
raise NotImplementedError(
-'''
-Abbreviation Extension for Python-Markdown
-==========================================
+# Abbreviation Extension for Python-Markdown
+# ==========================================
-This extension adds abbreviation handling to Python-Markdown.
+# This extension adds abbreviation handling to Python-Markdown.
+
+# See https://Python-Markdown.github.io/extensions/abbreviations
+# for documentation.
-See <https://Python-Markdown.github.io/extensions/abbreviations>
-for documentation.
+# Original code Copyright 2007-2008 [Waylan Limberg](http://achinghead.com/)
+# and [Seemant Kulleen](http://www.kulleen.org/)
-Oringinal code Copyright 2007-2008 [Waylan Limberg](http://achinghead.com/) and
- [Seemant Kulleen](http://www.kulleen.org/)
+# All changes Copyright 2008-2014 The Python Markdown Project
-All changes Copyright 2008-2014 The Python Markdown Project
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
+
+"""
+This extension adds abbreviation handling to Python-Markdown.
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+See the [documentation](https://Python-Markdown.github.io/extensions/abbreviations)
+for details.
+"""
-'''
+from __future__ import annotations
from . import Extension
from ..blockprocessors import BlockProcessor
""" Abbreviation Extension for Python-Markdown. """
def extendMarkdown(self, md):
- """ Insert AbbrPreprocessor before ReferencePreprocessor. """
+ """ Insert `AbbrPreprocessor` before `ReferencePreprocessor`. """
md.parser.blockprocessors.register(AbbrPreprocessor(md.parser), 'abbr', 16)
return True
def run(self, parent, blocks):
- '''
+ """
Find and remove all Abbreviation references from the text.
- Each reference is set as a new AbbrPattern in the markdown instance.
+ Each reference is set as a new `AbbrPattern` in the markdown instance.
- '''
+ """
block = blocks.pop(0)
m = self.RE.search(block)
if m:
return False
def _generate_pattern(self, text):
- '''
+ """
Given a string, returns an regex pattern to match that string.
'HTML' -> r'(?P<abbr>[H][T][M][L])'
Note: we force each char as a literal match (in brackets) as we don't
know what they will be beforehand.
- '''
+ """
chars = list(text)
for i in range(len(chars)):
chars[i] = r'[%s]' % chars[i]
-"""
-Admonition extension for Python-Markdown
-========================================
+# Admonition extension for Python-Markdown
+# ========================================
-Adds rST-style admonitions. Inspired by [rST][] feature with the same name.
+# Adds rST-style admonitions. Inspired by [rST][] feature with the same name.
+
+# [rST]: http://docutils.sourceforge.net/docs/ref/rst/directives.html#specific-admonitions
+
+# See https://Python-Markdown.github.io/extensions/admonition
+# for documentation.
-[rST]: http://docutils.sourceforge.net/docs/ref/rst/directives.html#specific-admonitions # noqa
+# Original code Copyright [Tiago Serafim](https://www.tiagoserafim.com/).
-See <https://Python-Markdown.github.io/extensions/admonition>
-for documentation.
+# All changes Copyright The Python Markdown Project
-Original code Copyright [Tiago Serafim](https://www.tiagoserafim.com/).
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
-All changes Copyright The Python Markdown Project
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+"""
+Adds rST-style admonitions. Inspired by [rST][] feature with the same name.
+[rST]: http://docutils.sourceforge.net/docs/ref/rst/directives.html#specific-admonitions
+
+See the [documentation](https://Python-Markdown.github.io/extensions/admonition)
+for details.
"""
+from __future__ import annotations
+
from . import Extension
from ..blockprocessors import BlockProcessor
import xml.etree.ElementTree as etree
sibling = self.lastChild(parent)
- if sibling is None or sibling.get('class', '').find(self.CLASSNAME) == -1:
+ if sibling is None or sibling.tag != 'div' or sibling.get('class', '').find(self.CLASSNAME) == -1:
sibling = None
else:
# If the last child is a list and the content is sufficiently indented
# to be under it, then the content's sibling is in the list.
last_child = self.lastChild(sibling)
indent = 0
- while last_child:
+ while last_child is not None:
if (
- sibling and block.startswith(' ' * self.tab_length * 2) and
- last_child and last_child.tag in ('ul', 'ol', 'dl')
+ sibling is not None and block.startswith(' ' * self.tab_length * 2) and
+ last_child is not None and last_child.tag in ('ul', 'ol', 'dl')
):
- # The expectation is that we'll find an <li> or <dt>.
+ # The expectation is that we'll find an `<li>` or `<dt>`.
# We should get its last child as well.
sibling = self.lastChild(last_child)
- last_child = self.lastChild(sibling) if sibling else None
+ last_child = self.lastChild(sibling) if sibling is not None else None
# Context has been lost at this point, so we must adjust the
# text's indentation level so it will be evaluated correctly
klass, title = match.group(1).lower(), match.group(2)
klass = self.RE_SPACES.sub(' ', klass)
if title is None:
- # no title was provided, use the capitalized classname as title
+ # no title was provided, use the capitalized class name as title
# e.g.: `!!! note` will render
# `<p class="admonition-title">Note</p>`
title = klass.split(' ', 1)[0].capitalize()
-"""
-Attribute List Extension for Python-Markdown
-============================================
+# Attribute List Extension for Python-Markdown
+# ============================================
-Adds attribute list syntax. Inspired by
-[maruku](http://maruku.rubyforge.org/proposal.html#attribute_lists)'s
-feature of the same name.
+# Adds attribute list syntax. Inspired by
+# [Maruku](http://maruku.rubyforge.org/proposal.html#attribute_lists)'s
+# feature of the same name.
-See <https://Python-Markdown.github.io/extensions/attr_list>
-for documentation.
+# See https://Python-Markdown.github.io/extensions/attr_list
+# for documentation.
-Original code Copyright 2011 [Waylan Limberg](http://achinghead.com/).
+# Original code Copyright 2011 [Waylan Limberg](http://achinghead.com/).
-All changes Copyright 2011-2014 The Python Markdown Project
+# All changes Copyright 2011-2014 The Python Markdown Project
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
"""
+ Adds attribute list syntax. Inspired by
+[Maruku](http://maruku.rubyforge.org/proposal.html#attribute_lists)'s
+feature of the same name.
+
+See the [documentation](https://Python-Markdown.github.io/extensions/attr_list)
+for details.
+"""
+
+from __future__ import annotations
+from typing import TYPE_CHECKING
from . import Extension
from ..treeprocessors import Treeprocessor
import re
+if TYPE_CHECKING: # pragma: no cover
+ from xml.etree.ElementTree import Element
+
def _handle_double_quote(s, t):
k, v = t.split('=', 1)
])
-def get_attrs(str):
+def get_attrs(str: str) -> list[tuple[str, str]]:
""" Parse attribute list and return a list of attribute tuples. """
return _scanner.scan(str)[0]
-def isheader(elem):
+def isheader(elem: Element) -> bool:
return elem.tag in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
r'\uf900-\ufdcf\ufdf0-\ufffd'
r'\:\-\.0-9\u00b7\u0300-\u036f\u203f-\u2040]+')
- def run(self, doc):
+ def run(self, doc: Element):
for elem in doc.iter():
if self.md.is_block_level(elem.tag):
- # Block level: check for attrs on last line of text
+ # Block level: check for `attrs` on last line of text
RE = self.BLOCK_RE
if isheader(elem) or elem.tag in ['dt', 'td', 'th']:
- # header, def-term, or table cell: check for attrs at end of element
+ # header, def-term, or table cell: check for attributes at end of element
RE = self.HEADER_RE
if len(elem) and elem.tag == 'li':
- # special case list items. children may include a ul or ol.
+ # special case list items. children may include a `ul` or `ol`.
pos = None
- # find the ul or ol position
+ # find the `ul` or `ol` position
for i, child in enumerate(elem):
if child.tag in ['ul', 'ol']:
pos = i
break
if pos is None and elem[-1].tail:
- # use tail of last child. no ul or ol.
+ # use tail of last child. no `ul` or `ol`.
m = RE.search(elem[-1].tail)
if m:
self.assign_attrs(elem, m.group(1))
elem[-1].tail = elem[-1].tail[:m.start()]
elif pos is not None and pos > 0 and elem[pos-1].tail:
- # use tail of last child before ul or ol
+ # use tail of last child before `ul` or `ol`
m = RE.search(elem[pos-1].tail)
if m:
self.assign_attrs(elem, m.group(1))
elem[pos-1].tail = elem[pos-1].tail[:m.start()]
elif elem.text:
- # use text. ul is first child.
+ # use text. `ul` is first child.
m = RE.search(elem.text)
if m:
self.assign_attrs(elem, m.group(1))
# clean up trailing #s
elem.text = elem.text.rstrip('#').rstrip()
else:
- # inline: check for attrs at start of tail
+ # inline: check for `attrs` at start of tail
if elem.tail:
m = self.INLINE_RE.match(elem.tail)
if m:
self.assign_attrs(elem, m.group(1))
elem.tail = elem.tail[m.end():]
- def assign_attrs(self, elem, attrs):
- """ Assign attrs to element. """
+ def assign_attrs(self, elem: Element, attrs: str) -> None:
+ """ Assign `attrs` to element. """
for k, v in get_attrs(attrs):
if k == '.':
# add to class
else:
elem.set('class', v)
else:
- # assign attr k with v
+ # assign attribute `k` with `v`
elem.set(self.sanitize_name(k), v)
- def sanitize_name(self, name):
+ def sanitize_name(self, name: str) -> str:
"""
Sanitize name as 'an XML Name, minus the ":"'.
See https://www.w3.org/TR/REC-xml-names/#NT-NCName
class AttrListExtension(Extension):
+ """ Attribute List extension for Python-Markdown """
def extendMarkdown(self, md):
md.treeprocessors.register(AttrListTreeprocessor(md), 'attr_list', 8)
md.registerExtension(self)
-"""
-CodeHilite Extension for Python-Markdown
-========================================
+# CodeHilite Extension for Python-Markdown
+# ========================================
-Adds code/syntax highlighting to standard Python-Markdown code blocks.
+# Adds code/syntax highlighting to standard Python-Markdown code blocks.
+
+# See https://Python-Markdown.github.io/extensions/code_hilite
+# for documentation.
-See <https://Python-Markdown.github.io/extensions/code_hilite>
-for documentation.
+# Original code Copyright 2006-2008 [Waylan Limberg](http://achinghead.com/).
-Original code Copyright 2006-2008 [Waylan Limberg](http://achinghead.com/).
+# All changes Copyright 2008-2014 The Python Markdown Project
-All changes Copyright 2008-2014 The Python Markdown Project
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+"""
+Adds code/syntax highlighting to standard Python-Markdown code blocks.
+See the [documentation](https://Python-Markdown.github.io/extensions/code_hilite)
+for details.
"""
+from __future__ import annotations
+
from . import Extension
from ..treeprocessors import Treeprocessor
from ..util import parseBoolValue
from pygments import highlight
from pygments.lexers import get_lexer_by_name, guess_lexer
from pygments.formatters import get_formatter_by_name
+ from pygments.util import ClassNotFound
pygments = True
except ImportError: # pragma: no cover
pygments = False
-def parse_hl_lines(expr):
+def parse_hl_lines(expr: str) -> list[int]:
"""Support our syntax for emphasizing certain lines of code.
- expr should be like '1 2' to emphasize lines 1 and 2 of a code block.
- Returns a list of ints, the line numbers to emphasize.
+ `expr` should be like '1 2' to emphasize lines 1 and 2 of a code block.
+ Returns a list of integers, the line numbers to emphasize.
"""
if not expr:
return []
Determine language of source code, and pass it on to the Pygments highlighter.
Usage:
- code = CodeHilite(src=some_code, lang='python')
- html = code.hilite()
-
- Arguments:
- * src: Source string or any object with a .readline attribute.
-
- * lang: String name of Pygments lexer to use for highlighting. Default: `None`.
- * guess_lang: Auto-detect which lexer to use. Ignored if `lang` is set to a valid
- value. Default: `True`.
+ ```python
+ code = CodeHilite(src=some_code, lang='python')
+ html = code.hilite()
+ ```
- * use_pygments: Pass code to pygments for code highlighting. If `False`, the code is
- instead wrapped for highlighting by a JavaScript library. Default: `True`.
-
- * linenums: An alias to Pygments `linenos` formatter option. Default: `None`.
-
- * css_class: An alias to Pygments `cssclass` formatter option. Default: 'codehilite'.
-
- * lang_prefix: Prefix prepended to the language when `use_pygments` is `False`.
- Default: "language-".
+ Arguments:
+ src: Source string or any object with a `.readline` attribute.
+
+ Keyword arguments:
+ lang (str): String name of Pygments lexer to use for highlighting. Default: `None`.
+ guess_lang (bool): Auto-detect which lexer to use.
+ Ignored if `lang` is set to a valid value. Default: `True`.
+ use_pygments (bool): Pass code to Pygments for code highlighting. If `False`, the code is
+ instead wrapped for highlighting by a JavaScript library. Default: `True`.
+ pygments_formatter (str): The name of a Pygments formatter or a formatter class used for
+ highlighting the code blocks. Default: `html`.
+ linenums (bool): An alias to Pygments `linenos` formatter option. Default: `None`.
+ css_class (str): An alias to Pygments `cssclass` formatter option. Default: 'codehilite'.
+ lang_prefix (str): Prefix prepended to the language. Default: "language-".
Other Options:
+
Any other options are accepted and passed on to the lexer and formatter. Therefore,
valid options include any options which are accepted by the `html` formatter or
whichever lexer the code's language uses. Note that most lexers do not have any
options. However, a few have very useful options, such as PHP's `startinline` option.
Any invalid options are ignored without error.
- Formatter options: https://pygments.org/docs/formatters/#HtmlFormatter
- Lexer Options: https://pygments.org/docs/lexers/
+ * **Formatter options**: <https://pygments.org/docs/formatters/#HtmlFormatter>
+ * **Lexer Options**: <https://pygments.org/docs/lexers/>
+
+ Additionally, when Pygments is enabled, the code's language is passed to the
+ formatter as an extra option `lang_str`, whose value being `{lang_prefix}{lang}`.
+ This option has no effect to the Pygments' builtin formatters.
Advanced Usage:
- code = CodeHilite(
- src = some_code,
- lang = 'php',
- startinline = True, # Lexer option. Snippet does not start with `<?php`.
- linenostart = 42, # Formatter option. Snippet starts on line 42.
- hl_lines = [45, 49, 50], # Formatter option. Highlight lines 45, 49, and 50.
- linenos = 'inline' # Formatter option. Avoid alignment problems.
- )
- html = code.hilite()
+
+ ```python
+ code = CodeHilite(
+ src = some_code,
+ lang = 'php',
+ startinline = True, # Lexer option. Snippet does not start with `<?php`.
+ linenostart = 42, # Formatter option. Snippet starts on line 42.
+ hl_lines = [45, 49, 50], # Formatter option. Highlight lines 45, 49, and 50.
+ linenos = 'inline' # Formatter option. Avoid alignment problems.
+ )
+ html = code.hilite()
+ ```
"""
- def __init__(self, src, **options):
+ def __init__(self, src: str, **options):
self.src = src
self.lang = options.pop('lang', None)
self.guess_lang = options.pop('guess_lang', True)
self.use_pygments = options.pop('use_pygments', True)
self.lang_prefix = options.pop('lang_prefix', 'language-')
+ self.pygments_formatter = options.pop('pygments_formatter', 'html')
if 'linenos' not in options:
options['linenos'] = options.pop('linenums', None)
if 'cssclass' not in options:
options['cssclass'] = options.pop('css_class', 'codehilite')
if 'wrapcode' not in options:
- # Override pygments default
+ # Override Pygments default
options['wrapcode'] = True
# Disallow use of `full` option
options['full'] = False
self.options = options
- def hilite(self, shebang=True):
+ def hilite(self, shebang=True) -> str:
"""
- Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with
- optional line numbers. The output should then be styled with css to
+ Pass code to the [Pygments](https://pygments.org/) highlighter with
+ optional line numbers. The output should then be styled with CSS to
your liking. No styles are applied by default - only styling hooks
- (i.e.: <span class="k">).
+ (i.e.: `<span class="k">`).
returns : A string of html.
lexer = get_lexer_by_name('text', **self.options)
except ValueError: # pragma: no cover
lexer = get_lexer_by_name('text', **self.options)
- formatter = get_formatter_by_name('html', **self.options)
+ if not self.lang:
+ # Use the guessed lexer's language instead
+ self.lang = lexer.aliases[0]
+ lang_str = f'{self.lang_prefix}{self.lang}'
+ if isinstance(self.pygments_formatter, str):
+ try:
+ formatter = get_formatter_by_name(self.pygments_formatter, **self.options)
+ except ClassNotFound:
+ formatter = get_formatter_by_name('html', **self.options)
+ else:
+ formatter = self.pygments_formatter(lang_str=lang_str, **self.options)
return highlight(self.src, lexer, formatter)
else:
- # just escape and build markup usable by JS highlighting libs
+ # just escape and build markup usable by JavaScript highlighting libraries
txt = self.src.replace('&', '&')
txt = txt.replace('<', '<')
txt = txt.replace('>', '>')
def _parseHeader(self):
"""
Determines language of a code block from shebang line and whether the
- said line should be removed or left in place. If the sheband line
+ said line should be removed or left in place. If the shebang line
contains a path (even a single /) then it is assumed to be a real
shebang line and left alone. However, if no path is given
- (e.i.: #!python or :::python) then it is assumed to be a mock shebang
+ (e.i.: `#!python` or `:::python`) then it is assumed to be a mock shebang
for language identification of a code fragment and removed from the
code block prior to processing for code highlighting. When a mock
- shebang (e.i: #!python) is found, line numbering is turned on. When
- colons are found in place of a shebang (e.i.: :::python), line
+ shebang (e.i: `#!python`) is found, line numbering is turned on. When
+ colons are found in place of a shebang (e.i.: `:::python`), line
numbering is left in the current state - off by default.
Also parses optional list of highlight lines, like:
return text
def run(self, root):
- """ Find code blocks and store in htmlStash. """
+ """ Find code blocks and store in `htmlStash`. """
blocks = root.iter('pre')
for block in blocks:
if len(block) == 1 and block[0].tag == 'code':
**local_config
)
placeholder = self.md.htmlStash.store(code.hilite())
- # Clear codeblock in etree instance
+ # Clear code block in `etree` instance
block.clear()
- # Change to p element which will later
+ # Change to `p` element which will later
# be removed when inserting raw html
block.tag = 'p'
block.text = placeholder
class CodeHiliteExtension(Extension):
- """ Add source code highlighting to markdown codeblocks. """
+ """ Add source code highlighting to markdown code blocks. """
def __init__(self, **kwargs):
# define default configs
self.config = {
- 'linenums': [None,
- "Use lines numbers. True|table|inline=yes, False=no, None=auto"],
- 'guess_lang': [True,
- "Automatic language detection - Default: True"],
- 'css_class': ["codehilite",
- "Set class name for wrapper <div> - "
- "Default: codehilite"],
- 'pygments_style': ['default',
- 'Pygments HTML Formatter Style '
- '(Colorscheme) - Default: default'],
- 'noclasses': [False,
- 'Use inline styles instead of CSS classes - '
- 'Default false'],
- 'use_pygments': [True,
- 'Use Pygments to Highlight code blocks. '
- 'Disable if using a JavaScript library. '
- 'Default: True'],
+ 'linenums': [
+ None, "Use lines numbers. True|table|inline=yes, False=no, None=auto. Default: `None`."
+ ],
+ 'guess_lang': [
+ True, "Automatic language detection - Default: `True`."
+ ],
+ 'css_class': [
+ "codehilite", "Set class name for wrapper <div> - Default: `codehilite`."
+ ],
+ 'pygments_style': [
+ 'default', 'Pygments HTML Formatter Style (Colorscheme). Default: `default`.'
+ ],
+ 'noclasses': [
+ False, 'Use inline styles instead of CSS classes - Default `False`.'
+ ],
+ 'use_pygments': [
+ True, 'Highlight code blocks with pygments. Disable if using a JavaScript library. Default: `True`.'
+ ],
'lang_prefix': [
- 'language-',
- 'Prefix prepended to the language when use_pygments is false. Default: "language-"'
- ]
- }
+ 'language-', 'Prefix prepended to the language when `use_pygments` is false. Default: `language-`.'
+ ],
+ 'pygments_formatter': [
+ 'html', 'Use a specific formatter for Pygments highlighting. Default: `html`.'
+ ],
+ }
+ """ Default configuration options. """
for key, value in kwargs.items():
if key in self.config:
# manually set unknown keywords.
if isinstance(value, str):
try:
- # Attempt to parse str as a bool value
+ # Attempt to parse `str` as a boolean value
value = parseBoolValue(value, preserve_none=True)
except ValueError:
- pass # Assume it's not a bool value. Use as-is.
+ pass # Assume it's not a boolean value. Use as-is.
self.config[key] = [value, '']
def extendMarkdown(self, md):
- """ Add HilitePostprocessor to Markdown instance. """
+ """ Add `HilitePostprocessor` to Markdown instance. """
hiliter = HiliteTreeprocessor(md)
hiliter.config = self.getConfigs()
md.treeprocessors.register(hiliter, 'hilite', 30)
-"""
-Definition List Extension for Python-Markdown
-=============================================
+# Definition List Extension for Python-Markdown
+# =============================================
-Adds parsing of Definition Lists to Python-Markdown.
+# Adds parsing of Definition Lists to Python-Markdown.
+
+# See https://Python-Markdown.github.io/extensions/definition_lists
+# for documentation.
-See <https://Python-Markdown.github.io/extensions/definition_lists>
-for documentation.
+# Original code Copyright 2008 [Waylan Limberg](http://achinghead.com)
-Original code Copyright 2008 [Waylan Limberg](http://achinghead.com)
+# All changes Copyright 2008-2014 The Python Markdown Project
-All changes Copyright 2008-2014 The Python Markdown Project
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+"""
+Adds parsing of Definition Lists to Python-Markdown.
+See the [documentation](https://Python-Markdown.github.io/extensions/definition_lists)
+for details.
"""
+from __future__ import annotations
+
from . import Extension
from ..blockprocessors import BlockProcessor, ListIndentProcessor
import xml.etree.ElementTree as etree
# Definition lists need to be aware of all list types
ITEM_TYPES = ['dd', 'li']
+ """ Include `dd` in list item types. """
LIST_TYPES = ['dl', 'ol', 'ul']
+ """ Include `dl` is list types. """
def create_item(self, parent, block):
- """ Create a new dd or li (depending on parent) and parse the block with it as the parent. """
+ """ Create a new `dd` or `li` (depending on parent) and parse the block with it as the parent. """
dd = etree.SubElement(parent, 'dd')
self.parser.parseBlocks(dd, [block])
""" Add definition lists to Markdown. """
def extendMarkdown(self, md):
- """ Add an instance of DefListProcessor to BlockParser. """
+ """ Add an instance of `DefListProcessor` to `BlockParser`. """
md.parser.blockprocessors.register(DefListIndentProcessor(md.parser), 'defindent', 85)
md.parser.blockprocessors.register(DefListProcessor(md.parser), 'deflist', 25)
-"""
-Python-Markdown Extra Extension
-===============================
+# Python-Markdown Extra Extension
+# ===============================
+
+# A compilation of various Python-Markdown extensions that imitates
+# [PHP Markdown Extra](http://michelf.com/projects/php-markdown/extra/).
+
+# See https://Python-Markdown.github.io/extensions/extra
+# for documentation.
+
+# Copyright The Python Markdown Project
+
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
+"""
A compilation of various Python-Markdown extensions that imitates
[PHP Markdown Extra](http://michelf.com/projects/php-markdown/extra/).
Note that each of the individual extensions still need to be available
-on your PYTHONPATH. This extension simply wraps them all up as a
+on your `PYTHONPATH`. This extension simply wraps them all up as a
convenience so that only one extension needs to be listed when
initiating Markdown. See the documentation for each individual
extension for specifics about that extension.
variable defined below, but be aware that such changes may be lost
when you upgrade to any future version of Python-Markdown.
-See <https://Python-Markdown.github.io/extensions/extra>
-for documentation.
-
-Copyright The Python Markdown Project
-
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
-
+See the [documentation](https://Python-Markdown.github.io/extensions/extra)
+for details.
"""
+from __future__ import annotations
+
from . import Extension
extensions = [
'abbr',
'md_in_html'
]
+""" The list of included extensions. """
class ExtraExtension(Extension):
""" Add various extensions to Markdown class."""
def __init__(self, **kwargs):
- """ config is a dumb holder which gets passed to actual ext later. """
+ """ `config` is a dumb holder which gets passed to the actual extension later. """
self.config = kwargs
def extendMarkdown(self, md):
-"""
-Fenced Code Extension for Python Markdown
-=========================================
+# Fenced Code Extension for Python Markdown
+# =========================================
-This extension adds Fenced Code Blocks to Python-Markdown.
+# This extension adds Fenced Code Blocks to Python-Markdown.
+
+# See https://Python-Markdown.github.io/extensions/fenced_code_blocks
+# for documentation.
-See <https://Python-Markdown.github.io/extensions/fenced_code_blocks>
-for documentation.
+# Original code Copyright 2007-2008 [Waylan Limberg](http://achinghead.com/).
-Original code Copyright 2007-2008 [Waylan Limberg](http://achinghead.com/).
+# All changes Copyright 2008-2014 The Python Markdown Project
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
-All changes Copyright 2008-2014 The Python Markdown Project
+"""
+This extension adds Fenced Code Blocks to Python-Markdown.
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+See the [documentation](https://Python-Markdown.github.io/extensions/fenced_code_blocks)
+for details.
"""
+from __future__ import annotations
from textwrap import dedent
from . import Extension
self.config = {
'lang_prefix': ['language-', 'Prefix prepended to the language. Default: "language-"']
}
+ """ Default configuration options. """
super().__init__(**kwargs)
def extendMarkdown(self, md):
- """ Add FencedBlockPreprocessor to the Markdown instance. """
+ """ Add `FencedBlockPreprocessor` to the Markdown instance. """
md.registerExtension(self)
md.preprocessors.register(FencedBlockPreprocessor(md, self.getConfigs()), 'fenced_code_block', 25)
class FencedBlockPreprocessor(Preprocessor):
+ """ Find and extract fenced code blocks. """
+
FENCED_BLOCK_RE = re.compile(
dedent(r'''
(?P<fence>^(?:~{3,}|`{3,}))[ ]* # opening fence
self.checked_for_deps = False
self.codehilite_conf = {}
self.use_attr_list = False
- # List of options to convert to bool values
+ # List of options to convert to boolean values
self.bool_options = [
'linenums',
'guess_lang',
]
def run(self, lines):
- """ Match and store Fenced Code Blocks in the HtmlStash. """
+ """ Match and store Fenced Code Blocks in the `HtmlStash`. """
# Check for dependent extensions
if not self.checked_for_deps:
if m.group('lang'):
lang = m.group('lang')
if m.group('hl_lines'):
- # Support hl_lines outside of attrs for backward-compatibility
+ # Support `hl_lines` outside of `attrs` for backward-compatibility
config['hl_lines'] = parse_hl_lines(m.group('hl_lines'))
- # If config is not empty, then the codehighlite extension
+ # If `config` is not empty, then the `codehighlite` extension
# is enabled, so we call it to highlight the code
if self.codehilite_conf and self.codehilite_conf['use_pygments'] and config.get('use_pygments', True):
local_config = self.codehilite_conf.copy()
local_config.update(config)
- # Combine classes with cssclass. Ensure cssclass is at end
- # as pygments appends a suffix under certain circumstances.
+ # Combine classes with `cssclass`. Ensure `cssclass` is at end
+ # as Pygments appends a suffix under certain circumstances.
# Ignore ID as Pygments does not offer an option to set it.
if classes:
local_config['css_class'] = '{} {}'.format(
if id:
id_attr = f' id="{_escape_attrib_html(id)}"'
if self.use_attr_list and config and not config.get('use_pygments', False):
- # Only assign key/value pairs to code element if attr_list ext is enabled, key/value pairs
- # were defined on the code block, and the `use_pygments` key was not set to True. The
- # `use_pygments` key could be either set to False or not defined. It is omitted from output.
+ # Only assign key/value pairs to code element if `attr_list` extension is enabled, key/value
+ # pairs were defined on the code block, and the `use_pygments` key was not set to `True`. The
+ # `use_pygments` key could be either set to `False` or not defined. It is omitted from output.
kv_pairs = ''.join(
f' {k}="{_escape_attrib_html(v)}"' for k, v in config.items() if k != 'use_pygments'
)
return text.split("\n")
def handle_attrs(self, attrs):
- """ Return tuple: (id, [list, of, classes], {configs}) """
+ """ Return tuple: `(id, [list, of, classes], {configs})` """
id = ''
classes = []
configs = {}
-"""
-Footnotes Extension for Python-Markdown
-=======================================
+# Footnotes Extension for Python-Markdown
+# =======================================
-Adds footnote handling to Python-Markdown.
+# Adds footnote handling to Python-Markdown.
-See <https://Python-Markdown.github.io/extensions/footnotes>
-for documentation.
+# See https://Python-Markdown.github.io/extensions/footnotes
+# for documentation.
-Copyright The Python Markdown Project
+# Copyright The Python Markdown Project
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
+
+"""
+Adds footnote handling to Python-Markdown.
+See the [documentation](https://Python-Markdown.github.io/extensions/footnotes)
+for details.
"""
+from __future__ import annotations
+
from . import Extension
from ..blockprocessors import BlockProcessor
from ..inlinepatterns import InlineProcessor
""" Setup configs. """
self.config = {
- 'PLACE_MARKER':
- ["///Footnotes Go Here///",
- "The text string that marks where the footnotes go"],
- 'UNIQUE_IDS':
- [False,
- "Avoid name collisions across "
- "multiple calls to reset()."],
- "BACKLINK_TEXT":
- ["↩",
- "The text string that links from the footnote "
- "to the reader's place."],
- "BACKLINK_TITLE":
- ["Jump back to footnote %d in the text",
- "The text string used for the title HTML attribute "
- "of the backlink. %d will be replaced by the "
- "footnote number."],
- "SEPARATOR":
- [":",
- "Footnote separator."]
+ 'PLACE_MARKER': [
+ '///Footnotes Go Here///', 'The text string that marks where the footnotes go'
+ ],
+ 'UNIQUE_IDS': [
+ False, 'Avoid name collisions across multiple calls to `reset()`.'
+ ],
+ 'BACKLINK_TEXT': [
+ '↩', "The text string that links from the footnote to the reader's place."
+ ],
+ 'SUPERSCRIPT_TEXT': [
+ '{}', "The text string that links from the reader's place to the footnote."
+ ],
+ 'BACKLINK_TITLE': [
+ 'Jump back to footnote %d in the text',
+ 'The text string used for the title HTML attribute of the backlink. '
+ '%d will be replaced by the footnote number.'
+ ],
+ 'SEPARATOR': [
+ ':', 'Footnote separator.'
+ ]
}
+ """ Default configuration options. """
super().__init__(**kwargs)
# In multiple invocations, emit links that don't get tangled.
md.registerExtension(self)
self.parser = md.parser
self.md = md
- # Insert a blockprocessor before ReferencePreprocessor
+ # Insert a `blockprocessor` before `ReferencePreprocessor`
md.parser.blockprocessors.register(FootnoteBlockProcessor(self), 'footnote', 17)
- # Insert an inline pattern before ImageReferencePattern
+ # Insert an inline pattern before `ImageReferencePattern`
FOOTNOTE_RE = r'\[\^([^\]]*)\]' # blah blah [^1] blah
md.inlinePatterns.register(FootnoteInlineProcessor(FOOTNOTE_RE, self), 'footnote', 175)
# Insert a tree-processor that would actually add the footnote div
- # This must be before all other treeprocessors (i.e., inline and
- # codehilite) so they can run on the the contents of the div.
+ # This must be before all other tree-processors (i.e., `inline` and
+ # `codehilite`) so they can run on the the contents of the div.
md.treeprocessors.register(FootnoteTreeprocessor(self), 'footnote', 50)
# Insert a tree-processor that will run after inline is done.
# In this tree-processor we want to check our duplicate footnote tracker
- # And add additional backrefs to the footnote pointing back to the
+ # And add additional `backrefs` to the footnote pointing back to the
# duplicated references.
md.treeprocessors.register(FootnotePostTreeprocessor(self), 'footnote-duplicate', 15)
# Insert a postprocessor after amp_substitute processor
md.postprocessors.register(FootnotePostprocessor(self), 'footnote', 25)
- def reset(self):
+ def reset(self) -> None:
""" Clear footnotes on reset, and prepare for distinct document. """
- self.footnotes = OrderedDict()
+ self.footnotes: OrderedDict[str, str] = OrderedDict()
self.unique_prefix += 1
self.found_refs = {}
self.used_refs = set()
- def unique_ref(self, reference, found=False):
+ def unique_ref(self, reference, found: bool = False):
""" Get a unique reference if there are duplicates. """
if not found:
return reference
res = finder(root)
return res
- def setFootnote(self, id, text):
+ def setFootnote(self, id, text) -> None:
""" Store a footnote for later retrieval. """
self.footnotes[id] = text
else:
return 'fn{}{}'.format(self.get_separator(), id)
- def makeFootnoteRefId(self, id, found=False):
+ def makeFootnoteRefId(self, id, found: bool = False):
""" Return footnote back-link id. """
if self.getConfig("UNIQUE_IDS"):
return self.unique_ref('fnref%s%d-%s' % (self.get_separator(), self.unique_prefix, id), found)
return self.unique_ref('fnref{}{}'.format(self.get_separator(), id), found)
def makeFootnotesDiv(self, root):
- """ Return div of footnotes as et Element. """
+ """ Return `div` of footnotes as `etree` Element. """
if not list(self.footnotes.keys()):
return None
ol = etree.SubElement(div, "ol")
surrogate_parent = etree.Element("div")
+ # Backward compatibility with old '%d' placeholder
+ backlink_title = self.getConfig("BACKLINK_TITLE").replace("%d", "{}")
+
for index, id in enumerate(self.footnotes.keys(), start=1):
li = etree.SubElement(ol, "li")
li.set("id", self.makeFootnoteId(id))
- # Parse footnote with surrogate parent as li cannot be used.
- # List block handlers have special logic to deal with li.
- # When we are done parsing, we will copy everything over to li.
+ # Parse footnote with surrogate parent as `li` cannot be used.
+ # List block handlers have special logic to deal with `li`.
+ # When we are done parsing, we will copy everything over to `li`.
self.parser.parseChunk(surrogate_parent, self.footnotes[id])
for el in list(surrogate_parent):
li.append(el)
backlink.set("class", "footnote-backref")
backlink.set(
"title",
- self.getConfig("BACKLINK_TITLE") % (index)
+ backlink_title.format(index)
)
backlink.text = FN_BACKLINK_TEXT
blocks.insert(0, block)
return False
- def detectTabbed(self, blocks):
- """ Find indented text and remove indent before further proccesing.
+ def detectTabbed(self, blocks) -> list[str]:
+ """ Find indented text and remove indent before further processing.
- Returns: a list of blocks with indentation removed.
+ Returns:
+ A list of blocks with indentation removed.
"""
fn_blocks = []
while blocks:
class FootnoteInlineProcessor(InlineProcessor):
- """ InlinePattern for footnote markers in a document's body text. """
+ """ `InlineProcessor` for footnote markers in a document's body text. """
def __init__(self, pattern, footnotes):
super().__init__(pattern)
sup.set('id', self.footnotes.makeFootnoteRefId(id, found=True))
a.set('href', '#' + self.footnotes.makeFootnoteId(id))
a.set('class', 'footnote-ref')
- a.text = str(list(self.footnotes.footnotes.keys()).index(id) + 1)
+ a.text = self.footnotes.getConfig("SUPERSCRIPT_TEXT").format(
+ list(self.footnotes.footnotes.keys()).index(id) + 1
+ )
return sup, m.start(0), m.end(0)
else:
return None, None, None
def __init__(self, footnotes):
self.footnotes = footnotes
- def add_duplicates(self, li, duplicates):
- """ Adjust current li and add the duplicates: fnref2, fnref3, etc. """
+ def add_duplicates(self, li, duplicates) -> None:
+ """ Adjust current `li` and add the duplicates: `fnref2`, `fnref3`, etc. """
for link in li.iter('a'):
# Find the link that needs to be duplicated.
if link.attrib.get('class', '') == 'footnote-backref':
link_id = '{}ref{}{}'.format(fn, self.footnotes.get_separator(), rest)
return self.footnotes.found_refs.get(link_id, 0)
- def handle_duplicates(self, parent):
+ def handle_duplicates(self, parent) -> None:
""" Find duplicate footnotes and format and add the duplicates. """
for li in list(parent):
# Check number of duplicates footnotes and insert
def makeExtension(**kwargs): # pragma: no cover
- """ Return an instance of the FootnoteExtension """
+ """ Return an instance of the `FootnoteExtension` """
return FootnoteExtension(**kwargs)
-"""
-Python Markdown
-
-A Python implementation of John Gruber's Markdown.
+# Python Markdown
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# A Python implementation of John Gruber's Markdown.
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-License: BSD (see LICENSE.md for details).
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
-Legacy Attributes Extension
-===========================
+# License: BSD (see LICENSE.md for details).
+"""
An extension to Python Markdown which implements legacy attributes.
Prior to Python-Markdown version 3.0, the Markdown class had an `enable_attributes`
keyword which was on by default and provided for attributes to be defined for elements
using the format `{@key=value}`. This extension is provided as a replacement for
-backward compatibility. New documents should be authored using attr_lists. However,
-numerious documents exist which have been using the old attribute format for many
+backward compatibility. New documents should be authored using `attr_lists`. However,
+numerous documents exist which have been using the old attribute format for many
years. This extension can be used to continue to render those documents correctly.
"""
+from __future__ import annotations
+
import re
from markdown.treeprocessors import Treeprocessor, isString
from markdown.extensions import Extension
class LegacyAttrExtension(Extension):
def extendMarkdown(self, md):
+ """ Add `LegacyAttrs` to Markdown instance. """
md.treeprocessors.register(LegacyAttrs(md), 'legacyattrs', 15)
-'''
-Legacy Em Extension for Python-Markdown
-=======================================
+# Legacy Em Extension for Python-Markdown
+# =======================================
-This extension provides legacy behavior for _connected_words_.
+# This extension provides legacy behavior for _connected_words_.
+
+# Copyright 2015-2018 The Python Markdown Project
-Copyright 2015-2018 The Python Markdown Project
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+"""
+This extension provides legacy behavior for _connected_words_.
+"""
-'''
+from __future__ import annotations
from . import Extension
from ..inlinepatterns import UnderscoreProcessor, EmStrongItem, EM_STRONG2_RE, STRONG_EM2_RE
def makeExtension(**kwargs): # pragma: no cover
- """ Return an instance of the LegacyEmExtension """
+ """ Return an instance of the `LegacyEmExtension` """
return LegacyEmExtension(**kwargs)
-"""
-Python-Markdown Markdown in HTML Extension
-===============================
+# Python-Markdown Markdown in HTML Extension
+# ===============================
-An implementation of [PHP Markdown Extra](http://michelf.com/projects/php-markdown/extra/)'s
-parsing of Markdown syntax in raw HTML.
+# An implementation of [PHP Markdown Extra](http://michelf.com/projects/php-markdown/extra/)'s
+# parsing of Markdown syntax in raw HTML.
+
+# See https://Python-Markdown.github.io/extensions/raw_html
+# for documentation.
-See <https://Python-Markdown.github.io/extensions/raw_html>
-for documentation.
+# Copyright The Python Markdown Project
-Copyright The Python Markdown Project
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+"""
+An implementation of [PHP Markdown Extra](http://michelf.com/projects/php-markdown/extra/)'s
+parsing of Markdown syntax in raw HTML.
+See the [documentation](https://Python-Markdown.github.io/extensions/raw_html)
+for details.
"""
+from __future__ import annotations
+
from . import Extension
from ..blockprocessors import BlockProcessor
from ..preprocessors import Preprocessor
class HTMLExtractorExtra(HTMLExtractor):
"""
- Override HTMLExtractor and create etree Elements for any elements which should have content parsed as Markdown.
+ Override `HTMLExtractor` and create `etree` `Elements` for any elements which should have content parsed as
+ Markdown.
"""
def __init__(self, md, *args, **kwargs):
super().close()
# Handle any unclosed tags.
if self.mdstack:
- # Close the outermost parent. handle_endtag will close all unclosed children.
+ # Close the outermost parent. `handle_endtag` will close all unclosed children.
self.handle_endtag(self.mdstack[0])
def get_element(self):
- """ Return element from treebuilder and reset treebuilder for later use. """
+ """ Return element from `treebuilder` and reset `treebuilder` for later use. """
element = self.treebuilder.close()
self.treebuilder = etree.TreeBuilder()
return element
def get_state(self, tag, attrs):
- """ Return state from tag and `markdown` attr. One of 'block', 'span', or 'off'. """
+ """ Return state from tag and `markdown` attribute. One of 'block', 'span', or 'off'. """
md_attr = attrs.get('markdown', '0')
if md_attr == 'markdown':
# `<tag markdown>` is the same as `<tag markdown='1'>`.
return
if tag in self.block_level_tags and (self.at_line_start() or self.intail):
- # Valueless attr (ex: `<tag checked>`) results in `[('checked', None)]`.
+ # Valueless attribute (ex: `<tag checked>`) results in `[('checked', None)]`.
# Convert to `{'checked': 'checked'}`.
attrs = {key: value if value is not None else key for key, value in attrs}
state = self.get_state(tag, attrs)
# Check if element has a tail
if not blank_line_re.match(
self.rawdata[self.line_offset + self.offset + len(self.get_endtag_text(tag)):]):
- # More content exists after endtag.
+ # More content exists after `endtag`.
self.intail = True
else:
# Treat orphan closing tag as a span level tag.
def parse_pi(self, i):
if self.at_line_start() or self.intail or self.mdstack:
- # The same override exists in HTMLExtractor without the check
- # for mdstack. Therefore, use HTMLExtractor's parent instead.
+ # The same override exists in `HTMLExtractor` without the check
+ # for `mdstack`. Therefore, use parent of `HTMLExtractor` instead.
return super(HTMLExtractor, self).parse_pi(i)
# This is not the beginning of a raw block so treat as plain data
# and avoid consuming any tags which may follow (see #1066).
def parse_html_declaration(self, i):
if self.at_line_start() or self.intail or self.mdstack:
- # The same override exists in HTMLExtractor without the check
- # for mdstack. Therefore, use HTMLExtractor's parent instead.
+ # The same override exists in `HTMLExtractor` without the check
+ # for `mdstack`. Therefore, use parent of `HTMLExtractor` instead.
return super(HTMLExtractor, self).parse_html_declaration(i)
# This is not the beginning of a raw block so treat as plain data
# and avoid consuming any tags which may follow (see #1066).
class MarkdownInHtmlProcessor(BlockProcessor):
- """Process Markdown Inside HTML Blocks which have been stored in the HtmlStash."""
+ """Process Markdown Inside HTML Blocks which have been stored in the `HtmlStash`."""
def test(self, parent, block):
- # ALways return True. `run` will return `False` it not a valid match.
+ # Always return True. `run` will return `False` it not a valid match.
return True
def parse_element_content(self, element):
"""
- Recursively parse the text content of an etree Element as Markdown.
+ Recursively parse the text content of an `etree` Element as Markdown.
Any block level elements generated from the Markdown will be inserted as children of the element in place
of the text content. All `markdown` attributes are removed. For any elements in which Markdown parsing has
- been disabled, the text content of it and its chidlren are wrapped in an `AtomicString`.
+ been disabled, the text content of it and its children are wrapped in an `AtomicString`.
"""
md_attr = element.attrib.pop('markdown', 'off')
element.insert(0, child)
elif md_attr == 'span':
- # Span level parsing will be handled by inlineprocessors.
+ # Span level parsing will be handled by inline processors.
# Walk children here to remove any `markdown` attributes.
for child in list(element):
self.parse_element_content(child)
# Cleanup stash. Replace element with empty string to avoid confusing postprocessor.
self.parser.md.htmlStash.rawHtmlBlocks.pop(index)
self.parser.md.htmlStash.rawHtmlBlocks.insert(index, '')
- # Confirm the match to the blockparser.
+ # Confirm the match to the `blockparser`.
return True
# No match found.
return False
class MarkdownInHTMLPostprocessor(RawHtmlPostprocessor):
def stash_to_string(self, text):
- """ Override default to handle any etree elements still in the stash. """
+ """ Override default to handle any `etree` elements still in the stash. """
if isinstance(text, etree.Element):
return self.md.serializer(text)
else:
# Replace raw HTML preprocessor
md.preprocessors.register(HtmlBlockPreprocessor(md), 'html_block', 20)
- # Add blockprocessor which handles the placeholders for etree elements
+ # Add `blockprocessor` which handles the placeholders for `etree` elements
md.parser.blockprocessors.register(
MarkdownInHtmlProcessor(md.parser), 'markdown_block', 105
)
-"""
-Meta Data Extension for Python-Markdown
-=======================================
+# Meta Data Extension for Python-Markdown
+# =======================================
-This extension adds Meta Data handling to markdown.
+# This extension adds Meta Data handling to markdown.
+
+# See https://Python-Markdown.github.io/extensions/meta_data
+# for documentation.
-See <https://Python-Markdown.github.io/extensions/meta_data>
-for documentation.
+# Original code Copyright 2007-2008 [Waylan Limberg](http://achinghead.com).
-Original code Copyright 2007-2008 [Waylan Limberg](http://achinghead.com).
+# All changes Copyright 2008-2014 The Python Markdown Project
-All changes Copyright 2008-2014 The Python Markdown Project
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+"""
+This extension adds Meta Data handling to markdown.
+See the [documentation](https://Python-Markdown.github.io/extensions/meta_data)
+for details.
"""
+from __future__ import annotations
+
from . import Extension
from ..preprocessors import Preprocessor
import re
""" Meta-Data extension for Python-Markdown. """
def extendMarkdown(self, md):
- """ Add MetaPreprocessor to Markdown instance. """
+ """ Add `MetaPreprocessor` to Markdown instance. """
md.registerExtension(self)
self.md = md
md.preprocessors.register(MetaPreprocessor(md), 'meta', 27)
- def reset(self):
+ def reset(self) -> None:
self.md.Meta = {}
-"""
-NL2BR Extension
-===============
+# `NL2BR` Extension
+# ===============
-A Python-Markdown extension to treat newlines as hard breaks; like
-GitHub-flavored Markdown does.
+# A Python-Markdown extension to treat newlines as hard breaks; like
+# GitHub-flavored Markdown does.
+
+# See https://Python-Markdown.github.io/extensions/nl2br
+# for documentation.
-See <https://Python-Markdown.github.io/extensions/nl2br>
-for documentation.
+# Original code Copyright 2011 [Brian Neal](https://deathofagremmie.com/)
-Oringinal code Copyright 2011 [Brian Neal](https://deathofagremmie.com/)
+# All changes Copyright 2011-2014 The Python Markdown Project
-All changes Copyright 2011-2014 The Python Markdown Project
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+"""
+A Python-Markdown extension to treat newlines as hard breaks; like
+GitHub-flavored Markdown does.
+See the [documentation](https://Python-Markdown.github.io/extensions/nl2br)
+for details.
"""
+from __future__ import annotations
+
from . import Extension
from ..inlinepatterns import SubstituteTagInlineProcessor
class Nl2BrExtension(Extension):
def extendMarkdown(self, md):
+ """ Add a `SubstituteTagInlineProcessor` to Markdown. """
br_tag = SubstituteTagInlineProcessor(BR_RE, 'br')
md.inlinePatterns.register(br_tag, 'nl', 5)
-"""
-Sane List Extension for Python-Markdown
-=======================================
+# Sane List Extension for Python-Markdown
+# =======================================
-Modify the behavior of Lists in Python-Markdown to act in a sane manor.
+# Modify the behavior of Lists in Python-Markdown to act in a sane manor.
+
+# See https://Python-Markdown.github.io/extensions/sane_lists
+# for documentation.
-See <https://Python-Markdown.github.io/extensions/sane_lists>
-for documentation.
+# Original code Copyright 2011 [Waylan Limberg](http://achinghead.com)
-Original code Copyright 2011 [Waylan Limberg](http://achinghead.com)
+# All changes Copyright 2011-2014 The Python Markdown Project
-All changes Copyright 2011-2014 The Python Markdown Project
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+"""
+Modify the behavior of Lists in Python-Markdown to act in a sane manor.
+See [documentation](https://Python-Markdown.github.io/extensions/sane_lists)
+for details.
"""
+from __future__ import annotations
+
from . import Extension
from ..blockprocessors import OListProcessor, UListProcessor
import re
class SaneOListProcessor(OListProcessor):
+ """ Override `SIBLING_TAGS` to not include `ul` and set `LAZY_OL` to `False`. """
SIBLING_TAGS = ['ol']
+ """ Exclude `ul` from list of siblings. """
LAZY_OL = False
+ """ Disable lazy list behavior. """
def __init__(self, parser):
super().__init__(parser)
class SaneUListProcessor(UListProcessor):
+ """ Override `SIBLING_TAGS` to not include `ol`. """
SIBLING_TAGS = ['ul']
+ """ Exclude `ol` from list of siblings. """
def __init__(self, parser):
super().__init__(parser)
-'''
-Smarty extension for Python-Markdown
-====================================
+# Smarty extension for Python-Markdown
+# ====================================
-Adds conversion of ASCII dashes, quotes and ellipses to their HTML
-entity equivalents.
+# Adds conversion of ASCII dashes, quotes and ellipses to their HTML
+# entity equivalents.
+
+# See https://Python-Markdown.github.io/extensions/smarty
+# for documentation.
-See <https://Python-Markdown.github.io/extensions/smarty>
-for documentation.
+# Author: 2013, Dmitry Shachnev <mitya57@gmail.com>
-Author: 2013, Dmitry Shachnev <mitya57@gmail.com>
+# All changes Copyright 2013-2014 The Python Markdown Project
-All changes Copyright 2013-2014 The Python Markdown Project
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+# SmartyPants license:
-SmartyPants license:
+# Copyright (c) 2003 John Gruber <https://daringfireball.net/>
+# All rights reserved.
- Copyright (c) 2003 John Gruber <https://daringfireball.net/>
- All rights reserved.
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are
- met:
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the
- distribution.
+# * Neither the name "SmartyPants" nor the names of its contributors
+# may be used to endorse or promote products derived from this
+# software without specific prior written permission.
- * Neither the name "SmartyPants" nor the names of its contributors
- may be used to endorse or promote products derived from this
- software without specific prior written permission.
+# This software is provided by the copyright holders and contributors "as
+# is" and any express or implied warranties, including, but not limited
+# to, the implied warranties of merchantability and fitness for a
+# particular purpose are disclaimed. In no event shall the copyright
+# owner or contributors be liable for any direct, indirect, incidental,
+# special, exemplary, or consequential damages (including, but not
+# limited to, procurement of substitute goods or services; loss of use,
+# data, or profits; or business interruption) however caused and on any
+# theory of liability, whether in contract, strict liability, or tort
+# (including negligence or otherwise) arising in any way out of the use
+# of this software, even if advised of the possibility of such damage.
- This software is provided by the copyright holders and contributors "as
- is" and any express or implied warranties, including, but not limited
- to, the implied warranties of merchantability and fitness for a
- particular purpose are disclaimed. In no event shall the copyright
- owner or contributors be liable for any direct, indirect, incidental,
- special, exemplary, or consequential damages (including, but not
- limited to, procurement of substitute goods or services; loss of use,
- data, or profits; or business interruption) however caused and on any
- theory of liability, whether in contract, strict liability, or tort
- (including negligence or otherwise) arising in any way out of the use
- of this software, even if advised of the possibility of such damage.
+# `smartypants.py` license:
-smartypants.py license:
+# `smartypants.py` is a derivative work of SmartyPants.
+# Copyright (c) 2004, 2007 Chad Miller <http://web.chad.org/>
- smartypants.py is a derivative work of SmartyPants.
- Copyright (c) 2004, 2007 Chad Miller <http://web.chad.org/>
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are
- met:
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the
- distribution.
+# This software is provided by the copyright holders and contributors "as
+# is" and any express or implied warranties, including, but not limited
+# to, the implied warranties of merchantability and fitness for a
+# particular purpose are disclaimed. In no event shall the copyright
+# owner or contributors be liable for any direct, indirect, incidental,
+# special, exemplary, or consequential damages (including, but not
+# limited to, procurement of substitute goods or services; loss of use,
+# data, or profits; or business interruption) however caused and on any
+# theory of liability, whether in contract, strict liability, or tort
+# (including negligence or otherwise) arising in any way out of the use
+# of this software, even if advised of the possibility of such damage.
- This software is provided by the copyright holders and contributors "as
- is" and any express or implied warranties, including, but not limited
- to, the implied warranties of merchantability and fitness for a
- particular purpose are disclaimed. In no event shall the copyright
- owner or contributors be liable for any direct, indirect, incidental,
- special, exemplary, or consequential damages (including, but not
- limited to, procurement of substitute goods or services; loss of use,
- data, or profits; or business interruption) however caused and on any
- theory of liability, whether in contract, strict liability, or tort
- (including negligence or otherwise) arising in any way out of the use
- of this software, even if advised of the possibility of such damage.
+"""
+Adds conversion of ASCII dashes, quotes and ellipses to their HTML
+entity equivalents.
-'''
+See the [documentation](https://Python-Markdown.github.io/extensions/smarty)
+for details.
+"""
+from __future__ import annotations
from . import Extension
from ..inlinepatterns import HtmlInlineProcessor, HTML_RE
from ..treeprocessors import InlineProcessor
-from ..util import Registry, deprecated
+from ..util import Registry
# Constants for quote education.
r'(\s' # a whitespace char
r'| ' # or a non-breaking space entity
r'|--' # or dashes
- r'|–|—' # or unicode
+ r'|–|—' # or Unicode
r'|&[mn]dash;' # or named dash entities
r'|–|—' # or decimal entities
r')'
# Single closing quotes:
closingSingleQuotesRegex = r"(?<=%s)'(?!\s|s\b|\d)" % closeClass
-closingSingleQuotesRegex2 = r"(?<=%s)'(\s|s\b)" % closeClass
+closingSingleQuotesRegex2 = r"'(\s|s\b)"
# All remaining quotes should be opening ones
remainingSingleQuotesRegex = r"'"
self.replace = replace
self.md = md
- @property
- @deprecated("Use 'md' instead.")
- def markdown(self):
- # TODO: remove this later
- return self.md
-
def handleMatch(self, m, data):
result = ''
for part in self.replace:
class SmartyExtension(Extension):
+ """ Add Smarty to Markdown. """
def __init__(self, **kwargs):
self.config = {
'smart_quotes': [True, 'Educate quotes'],
'smart_ellipses': [True, 'Educate ellipses'],
'substitutions': [{}, 'Overwrite default substitutions'],
}
+ """ Default configuration options. """
super().__init__(**kwargs)
self.substitutions = dict(substitutions)
self.substitutions.update(self.getConfig('substitutions', default={}))
name = 'smarty-%s-%d' % (serie, ind)
self.inlinePatterns.register(pattern, name, priority-ind)
- def educateDashes(self, md):
+ def educateDashes(self, md) -> None:
emDashesPattern = SubstituteTextPattern(
r'(?<!-)---(?!-)', (self.substitutions['mdash'],), md
)
self.inlinePatterns.register(emDashesPattern, 'smarty-em-dashes', 50)
self.inlinePatterns.register(enDashesPattern, 'smarty-en-dashes', 45)
- def educateEllipses(self, md):
+ def educateEllipses(self, md) -> None:
ellipsesPattern = SubstituteTextPattern(
r'(?<!\.)\.{3}(?!\.)', (self.substitutions['ellipsis'],), md
)
self.inlinePatterns.register(ellipsesPattern, 'smarty-ellipses', 10)
- def educateAngledQuotes(self, md):
+ def educateAngledQuotes(self, md) -> None:
leftAngledQuotePattern = SubstituteTextPattern(
r'\<\<', (self.substitutions['left-angle-quote'],), md
)
self.inlinePatterns.register(leftAngledQuotePattern, 'smarty-left-angle-quotes', 40)
self.inlinePatterns.register(rightAngledQuotePattern, 'smarty-right-angle-quotes', 35)
- def educateQuotes(self, md):
+ def educateQuotes(self, md) -> None:
lsquo = self.substitutions['left-single-quote']
rsquo = self.substitutions['right-single-quote']
ldquo = self.substitutions['left-double-quote']
def extendMarkdown(self, md):
configs = self.getConfigs()
- self.inlinePatterns = Registry()
+ self.inlinePatterns: Registry[HtmlInlineProcessor] = Registry()
if configs['smart_ellipses']:
self.educateEllipses(md)
if configs['smart_quotes']:
self.educateQuotes(md)
if configs['smart_angled_quotes']:
self.educateAngledQuotes(md)
- # Override HTML_RE from inlinepatterns.py so that it does not
+ # Override `HTML_RE` from `inlinepatterns.py` so that it does not
# process tags with duplicate closing quotes.
md.inlinePatterns.register(HtmlInlineProcessor(HTML_STRICT_RE, md), 'html', 90)
if configs['smart_dashes']:
-"""
-Tables Extension for Python-Markdown
-====================================
+# Tables Extension for Python-Markdown
+# ====================================
-Added parsing of tables to Python-Markdown.
+# Added parsing of tables to Python-Markdown.
+
+# See https://Python-Markdown.github.io/extensions/tables
+# for documentation.
-See <https://Python-Markdown.github.io/extensions/tables>
-for documentation.
+# Original code Copyright 2009 [Waylan Limberg](http://achinghead.com)
-Original code Copyright 2009 [Waylan Limberg](http://achinghead.com)
+# All changes Copyright 2008-2014 The Python Markdown Project
-All changes Copyright 2008-2014 The Python Markdown Project
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+"""
+Added parsing of tables to Python-Markdown.
+See the [documentation](https://Python-Markdown.github.io/extensions/tables)
+for details.
"""
+from __future__ import annotations
+
from . import Extension
from ..blockprocessors import BlockProcessor
import xml.etree.ElementTree as etree
RE_CODE_PIPES = re.compile(r'(?:(\\\\)|(\\`+)|(`+)|(\\\|)|(\|))')
RE_END_BORDER = re.compile(r'(?<!\\)(?:\\\\)*\|$')
- def __init__(self, parser):
+ def __init__(self, parser, config):
self.border = False
self.separator = ''
+ self.config = config
+
super().__init__(parser)
def test(self, parent, block):
except IndexError: # pragma: no cover
c.text = ""
if a:
- c.set('align', a)
+ if self.config['use_align_attribute']:
+ c.set('align', a)
+ else:
+ c.set('style', f'text-align: {a};')
def _split_row(self, row):
""" split a row of text into list of cells. """
class TableExtension(Extension):
""" Add tables to Markdown. """
+ def __init__(self, **kwargs):
+ self.config = {
+ 'use_align_attribute': [False, 'True to use align attribute instead of style.'],
+ }
+ """ Default configuration options. """
+
+ super().__init__(**kwargs)
+
def extendMarkdown(self, md):
- """ Add an instance of TableProcessor to BlockParser. """
+ """ Add an instance of `TableProcessor` to `BlockParser`. """
if '|' not in md.ESCAPED_CHARS:
md.ESCAPED_CHARS.append('|')
- md.parser.blockprocessors.register(TableProcessor(md.parser), 'table', 75)
+ processor = TableProcessor(md.parser, self.getConfigs())
+ md.parser.blockprocessors.register(processor, 'table', 75)
def makeExtension(**kwargs): # pragma: no cover
-"""
-Table of Contents Extension for Python-Markdown
-===============================================
+# Table of Contents Extension for Python-Markdown
+# ===============================================
+
+# See https://Python-Markdown.github.io/extensions/toc
+# for documentation.
-See <https://Python-Markdown.github.io/extensions/toc>
-for documentation.
+# Original code Copyright 2008 [Jack Miller](https://codezen.org/)
-Oringinal code Copyright 2008 [Jack Miller](https://codezen.org/)
+# All changes Copyright 2008-2014 The Python Markdown Project
-All changes Copyright 2008-2014 The Python Markdown Project
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+"""
+Add table of contents support to Python-Markdown.
+See the [documentation](https://Python-Markdown.github.io/extensions/toc)
+for details.
"""
+from __future__ import annotations
+
from . import Extension
from ..treeprocessors import Treeprocessor
from ..util import code_escape, parseBoolValue, AMP_SUBSTITUTE, HTML_PLACEHOLDER_RE, AtomicString
-from ..postprocessors import UnescapePostprocessor
+from ..treeprocessors import UnescapeTreeprocessor
import re
import html
import unicodedata
def slugify(value, separator, unicode=False):
""" Slugify a string, to make it URL friendly. """
if not unicode:
- # Replace Extended Latin characters with ASCII, i.e. žlutý → zluty
+ # Replace Extended Latin characters with ASCII, i.e. `žlutý` => `zluty`
value = unicodedata.normalize('NFKD', value)
value = value.encode('ascii', 'ignore').decode('ascii')
value = re.sub(r'[^\w\s-]', '', value).strip().lower()
return ''.join(text).strip()
-def stashedHTML2text(text, md, strip_entities=True):
+def stashedHTML2text(text, md, strip_entities: bool = True):
""" Extract raw HTML from stash, reduce to plain text and swap with placeholder. """
def _html_sub(m):
""" Substitute raw html with plain text. """
def unescape(text):
""" Unescape escaped text. """
- c = UnescapePostprocessor()
- return c.run(text)
+ c = UnescapeTreeprocessor()
+ return c.unescape(text)
def nest_toc_tokens(toc_list):
"""Given an unsorted list with errors and skips, return a nested one.
- [{'level': 1}, {'level': 2}]
- =>
- [{'level': 1, 'children': [{'level': 2, 'children': []}]}]
+
+ [{'level': 1}, {'level': 2}]
+ =>
+ [{'level': 1, 'children': [{'level': 2, 'children': []}]}]
A wrong list is also converted:
- [{'level': 2}, {'level': 1}]
- =>
- [{'level': 2, 'children': []}, {'level': 1, 'children': []}]
+
+ [{'level': 2}, {'level': 1}]
+ =>
+ [{'level': 2, 'children': []}, {'level': 1, 'children': []}]
"""
ordered_list = []
class TocTreeprocessor(Treeprocessor):
+ """ Step through document and build TOC. """
+
def __init__(self, md, config):
super().__init__(md)
self.base_level = int(config["baselevel"]) - 1
self.slugify = config["slugify"]
self.sep = config["separator"]
+ self.toc_class = config["toc_class"]
+ self.title_class = config["title_class"]
self.use_anchors = parseBoolValue(config["anchorlink"])
self.anchorlink_class = config["anchorlink_class"]
self.use_permalinks = parseBoolValue(config["permalink"], False)
self.use_permalinks = config["permalink"]
self.permalink_class = config["permalink_class"]
self.permalink_title = config["permalink_title"]
+ self.permalink_leading = parseBoolValue(config["permalink_leading"], False)
self.header_rgx = re.compile("[Hh][123456]")
if isinstance(config["toc_depth"], str) and '-' in config["toc_depth"]:
self.toc_top, self.toc_bottom = [int(x) for x in config["toc_depth"].split('-')]
self.toc_bottom = int(config["toc_depth"])
def iterparent(self, node):
- ''' Iterator wrapper to get allowed parent and child all at once. '''
+ """ Iterator wrapper to get allowed parent and child all at once. """
# We do not allow the marker inside a header as that
- # would causes an enless loop of placing a new TOC
+ # would causes an endless loop of placing a new TOC
# inside previously generated TOC.
for child in node:
if not self.header_rgx.match(child.tag) and child.tag not in ['pre', 'code']:
yield node, child
yield from self.iterparent(child)
- def replace_marker(self, root, elem):
- ''' Replace marker with elem. '''
+ def replace_marker(self, root, elem) -> None:
+ """ Replace marker with elem. """
for (p, c) in self.iterparent(root):
text = ''.join(c.itertext()).strip()
if not text:
continue
# To keep the output from screwing up the
- # validation by putting a <div> inside of a <p>
- # we actually replace the <p> in its entirety.
+ # validation by putting a `<div>` inside of a `<p>`
+ # we actually replace the `<p>` in its entirety.
- # The <p> element may contain more than a single text content
- # (nl2br can introduce a <br>). In this situation, c.text returns
+ # The `<p>` element may contain more than a single text content
+ # (`nl2br` can introduce a `<br>`). In this situation, `c.text` returns
# the very first content, ignore children contents or tail content.
- # len(c) == 0 is here to ensure there is only text in the <p>.
+ # `len(c) == 0` is here to ensure there is only text in the `<p>`.
if c.text and c.text.strip() == self.marker and len(c) == 0:
for i in range(len(p)):
if p[i] == c:
p[i] = elem
break
- def set_level(self, elem):
- ''' Adjust header level according to base level. '''
+ def set_level(self, elem) -> None:
+ """ Adjust header level according to base level. """
level = int(elem.tag[-1]) + self.base_level
if level > 6:
level = 6
elem.tag = 'h%d' % level
- def add_anchor(self, c, elem_id): # @ReservedAssignment
+ def add_anchor(self, c, elem_id) -> None:
anchor = etree.Element("a")
anchor.text = c.text
anchor.attrib["href"] = "#" + elem_id
c.remove(c[0])
c.append(anchor)
- def add_permalink(self, c, elem_id):
+ def add_permalink(self, c, elem_id) -> None:
permalink = etree.Element("a")
permalink.text = ("%spara;" % AMP_SUBSTITUTE
if self.use_permalinks is True
permalink.attrib["class"] = self.permalink_class
if self.permalink_title:
permalink.attrib["title"] = self.permalink_title
- c.append(permalink)
+ if self.permalink_leading:
+ permalink.tail = c.text
+ c.text = ""
+ c.insert(0, permalink)
+ else:
+ c.append(permalink)
def build_toc_div(self, toc_list):
""" Return a string div given a toc list. """
div = etree.Element("div")
- div.attrib["class"] = "toc"
+ div.attrib["class"] = self.toc_class
# Add title to the div
if self.title:
header = etree.SubElement(div, "span")
- header.attrib["class"] = "toctitle"
+ if self.title_class:
+ header.attrib["class"] = self.title_class
header.text = self.title
def build_etree_ul(toc_list, parent):
def __init__(self, **kwargs):
self.config = {
- "marker": ['[TOC]',
- 'Text to find and replace with Table of Contents - '
- 'Set to an empty string to disable. Defaults to "[TOC]"'],
- "title": ["",
- "Title to insert into TOC <div> - "
- "Defaults to an empty string"],
- "anchorlink": [False,
- "True if header should be a self link - "
- "Defaults to False"],
- "anchorlink_class": ['toclink',
- 'CSS class(es) used for the link. '
- 'Defaults to "toclink"'],
- "permalink": [0,
- "True or link text if a Sphinx-style permalink should "
- "be added - Defaults to False"],
- "permalink_class": ['headerlink',
- 'CSS class(es) used for the link. '
- 'Defaults to "headerlink"'],
- "permalink_title": ["Permanent link",
- "Title attribute of the permalink - "
- "Defaults to 'Permanent link'"],
- "baselevel": ['1', 'Base level for headers.'],
- "slugify": [slugify,
- "Function to generate anchors based on header text - "
- "Defaults to the headerid ext's slugify function."],
- 'separator': ['-', 'Word separator. Defaults to "-".'],
- "toc_depth": [6,
- 'Define the range of section levels to include in'
- 'the Table of Contents. A single integer (b) defines'
- 'the bottom section level (<h1>..<hb>) only.'
- 'A string consisting of two digits separated by a hyphen'
- 'in between ("2-5"), define the top (t) and the'
- 'bottom (b) (<ht>..<hb>). Defaults to `6` (bottom).'],
+ 'marker': [
+ '[TOC]',
+ 'Text to find and replace with Table of Contents. Set to an empty string to disable. '
+ 'Default: `[TOC]`.'
+ ],
+ 'title': [
+ '', 'Title to insert into TOC `<div>`. Default: an empty string.'
+ ],
+ 'title_class': [
+ 'toctitle', 'CSS class used for the title. Default: `toctitle`.'
+ ],
+ 'toc_class': [
+ 'toc', 'CSS class(es) used for the link. Default: `toclink`.'
+ ],
+ 'anchorlink': [
+ False, 'True if header should be a self link. Default: `False`.'
+ ],
+ 'anchorlink_class': [
+ 'toclink', 'CSS class(es) used for the link. Defaults: `toclink`.'
+ ],
+ 'permalink': [
+ 0, 'True or link text if a Sphinx-style permalink should be added. Default: `False`.'
+ ],
+ 'permalink_class': [
+ 'headerlink', 'CSS class(es) used for the link. Default: `headerlink`.'
+ ],
+ 'permalink_title': [
+ 'Permanent link', 'Title attribute of the permalink. Default: `Permanent link`.'
+ ],
+ 'permalink_leading': [
+ False,
+ 'True if permalinks should be placed at start of the header, rather than end. Default: False.'
+ ],
+ 'baselevel': ['1', 'Base level for headers. Default: `1`.'],
+ 'slugify': [
+ slugify, 'Function to generate anchors based on header text. Default: `slugify`.'
+ ],
+ 'separator': ['-', 'Word separator. Default: `-`.'],
+ 'toc_depth': [
+ 6,
+ 'Define the range of section levels to include in the Table of Contents. A single integer '
+ '(b) defines the bottom section level (<h1>..<hb>) only. A string consisting of two digits '
+ 'separated by a hyphen in between (`2-5`) defines the top (t) and the bottom (b) (<ht>..<hb>). '
+ 'Default: `6` (bottom).'
+ ],
}
+ """ Default configuration options. """
super().__init__(**kwargs)
def extendMarkdown(self, md):
+ """ Add TOC tree processor to Markdown. """
md.registerExtension(self)
self.md = md
self.reset()
tocext = self.TreeProcessorClass(md, self.getConfigs())
- # Headerid ext is set to '>prettify'. With this set to '_end',
- # it should always come after headerid ext (and honor ids assigned
- # by the header id extension) if both are used. Same goes for
- # attr_list extension. This must come last because we don't want
- # to redefine ids after toc is created. But we do want toc prettified.
md.treeprocessors.register(tocext, 'toc', 5)
- def reset(self):
+ def reset(self) -> None:
self.md.toc = ''
self.md.toc_tokens = []
-'''
-WikiLinks Extension for Python-Markdown
-======================================
+# WikiLinks Extension for Python-Markdown
+# ======================================
-Converts [[WikiLinks]] to relative links.
+# Converts [[WikiLinks]] to relative links.
-See <https://Python-Markdown.github.io/extensions/wikilinks>
-for documentation.
+# See https://Python-Markdown.github.io/extensions/wikilinks
+# for documentation.
-Original code Copyright [Waylan Limberg](http://achinghead.com/).
+# Original code Copyright [Waylan Limberg](http://achinghead.com/).
-All changes Copyright The Python Markdown Project
+# All changes Copyright The Python Markdown Project
-License: [BSD](https://opensource.org/licenses/bsd-license.php)
+# License: [BSD](https://opensource.org/licenses/bsd-license.php)
-'''
+"""
+Converts `[[WikiLinks]]` to relative links.
+
+See the [documentation](https://Python-Markdown.github.io/extensions/wikilinks)
+for details.
+"""
+
+from __future__ import annotations
from . import Extension
from ..inlinepatterns import InlineProcessor
def build_url(label, base, end):
- """ Build a url from the label, a base, and an end. """
+ """ Build a URL from the label, a base, and an end. """
clean_label = re.sub(r'([ ]+_)|(_[ ]+)|([ ]+)', '_', label)
return '{}{}{}'.format(base, clean_label, end)
class WikiLinkExtension(Extension):
+ """ Add inline processor to Markdown. """
def __init__(self, **kwargs):
self.config = {
'html_class': ['wikilink', 'CSS hook. Leave blank for none.'],
'build_url': [build_url, 'Callable formats URL from label.'],
}
-
+ """ Default configuration options. """
super().__init__(**kwargs)
def extendMarkdown(self, md):
class WikiLinksInlineProcessor(InlineProcessor):
+ """ Build link from `wikilink`. """
+
def __init__(self, pattern, config):
super().__init__(pattern)
self.config = config
return a, m.start(0), m.end(0)
def _getMeta(self):
- """ Return meta data or config data. """
+ """ Return meta data or `config` data. """
base_url = self.config['base_url']
end_url = self.config['end_url']
html_class = self.config['html_class']
-"""
-Python Markdown
+# Python Markdown
+
+# A Python implementation of John Gruber's Markdown.
-A Python implementation of John Gruber's Markdown.
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
-Copyright 2007-2020 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# License: BSD (see LICENSE.md for details).
-License: BSD (see LICENSE.md for details).
+"""
+This module imports a copy of [`html.parser.HTMLParser`][] and modifies it heavily through monkey-patches.
+A copy is imported rather than the module being directly imported as this ensures that the user can import
+and use the unmodified library for their own needs.
"""
+from __future__ import annotations
+
import re
-import importlib
+import importlib.util
import sys
spec.loader.exec_module(htmlparser)
sys.modules['htmlparser'] = htmlparser
-# Monkeypatch HTMLParser to only accept `?>` to close Processing Instructions.
+# Monkeypatch `HTMLParser` to only accept `?>` to close Processing Instructions.
htmlparser.piclose = re.compile(r'\?>')
-# Monkeypatch HTMLParser to only recognize entity references with a closing semicolon.
+# Monkeypatch `HTMLParser` to only recognize entity references with a closing semicolon.
htmlparser.entityref = re.compile(r'&([a-zA-Z][-.a-zA-Z0-9]*);')
-# Monkeypatch HTMLParser to no longer support partial entities. We are always feeding a complete block,
-# so the 'incomplete' functionality is unnecessary. As the entityref regex is run right before incomplete,
+# Monkeypatch `HTMLParser` to no longer support partial entities. We are always feeding a complete block,
+# so the 'incomplete' functionality is unnecessary. As the `entityref` regex is run right before incomplete,
# and the two regex are the same, then incomplete will simply never match and we avoid the logic within.
htmlparser.incomplete = htmlparser.entityref
-# Monkeypatch HTMLParser to not accept a backtick in a tag name, attribute name, or bare value.
+# Monkeypatch `HTMLParser` to not accept a backtick in a tag name, attribute name, or bare value.
htmlparser.locatestarttagend_tolerant = re.compile(r"""
<[a-zA-Z][^`\t\n\r\f />\x00]* # tag name <= added backtick here
(?:[\s/]* # optional whitespace before attribute name
"""
Extract raw HTML from text.
- The raw HTML is stored in the `htmlStash` of the Markdown instance passed
- to `md` and the remaining text is stored in `cleandoc` as a list of strings.
+ The raw HTML is stored in the [`htmlStash`][markdown.util.HtmlStash] of the
+ [`Markdown`][markdown.Markdown] instance passed to `md` and the remaining text
+ is stored in `cleandoc` as a list of strings.
"""
def __init__(self, md, *args, **kwargs):
# Block tags that should contain no content (self closing)
self.empty_tags = set(['hr'])
+ self.lineno_start_cache = [0]
+
# This calls self.reset
super().__init__(*args, **kwargs)
self.md = md
"""Reset this instance. Loses all unprocessed data."""
self.inraw = False
self.intail = False
- self.stack = [] # When inraw==True, stack contains a list of tags
+ self.stack = [] # When `inraw==True`, stack contains a list of tags
self._cache = []
self.cleandoc = []
+ self.lineno_start_cache = [0]
+
super().reset()
def close(self):
self._cache = []
@property
- def line_offset(self):
- """Returns char index in self.rawdata for the start of the current line. """
- if self.lineno > 1 and '\n' in self.rawdata:
- m = re.match(r'([^\n]*\n){{{}}}'.format(self.lineno-1), self.rawdata)
- if m:
- return m.end()
- else: # pragma: no cover
- # Value of self.lineno must exceed total number of lines.
- # Find index of beginning of last line.
- return self.rawdata.rfind('\n')
- return 0
-
- def at_line_start(self):
+ def line_offset(self) -> int:
+ """Returns char index in `self.rawdata` for the start of the current line. """
+ for ii in range(len(self.lineno_start_cache)-1, self.lineno-1):
+ last_line_start_pos = self.lineno_start_cache[ii]
+ lf_pos = self.rawdata.find('\n', last_line_start_pos)
+ if lf_pos == -1:
+ # No more newlines found. Use end of raw data as start of line beyond end.
+ lf_pos = len(self.rawdata)
+ self.lineno_start_cache.append(lf_pos+1)
+
+ return self.lineno_start_cache[self.lineno-1]
+
+ def at_line_start(self) -> bool:
"""
Returns True if current position is at start of line.
# Confirm up to first 3 chars are whitespace
return self.rawdata[self.line_offset:self.line_offset + self.offset].strip() == ''
- def get_endtag_text(self, tag):
+ def get_endtag_text(self, tag: str) -> str:
"""
Returns the text of the end tag.
# Failed to extract from raw data. Assume well formed and lowercase.
return '</{}>'.format(tag)
- def handle_starttag(self, tag, attrs):
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str]]):
# Handle tags that should always be empty and do not specify a closing tag
if tag in self.empty_tags:
self.handle_startendtag(tag, attrs)
# This is presumably a standalone tag in a code span (see #1036).
self.clear_cdata_mode()
- def handle_endtag(self, tag):
+ def handle_endtag(self, tag: str):
text = self.get_endtag_text(tag)
if self.inraw:
# Preserve blank line and end of raw block.
self._cache.append('\n')
else:
- # More content exists after endtag.
+ # More content exists after `endtag`.
self.intail = True
# Reset stack.
self.inraw = False
else:
self.cleandoc.append(text)
- def handle_data(self, data):
+ def handle_data(self, data: str):
if self.intail and '\n' in data:
self.intail = False
if self.inraw:
else:
self.cleandoc.append(data)
- def handle_empty_tag(self, data, is_block):
+ def handle_empty_tag(self, data: str, is_block: bool):
""" Handle empty tags (`<data>`). """
if self.inraw or self.intail:
# Append this to the existing raw block
else:
self.cleandoc.append(data)
- def handle_startendtag(self, tag, attrs):
+ def handle_startendtag(self, tag: str, attrs: list[tuple[str, str]]):
self.handle_empty_tag(self.get_starttag_text(), is_block=self.md.is_block_level(tag))
- def handle_charref(self, name):
+ def handle_charref(self, name: str):
self.handle_empty_tag('&#{};'.format(name), is_block=False)
- def handle_entityref(self, name):
+ def handle_entityref(self, name: str):
self.handle_empty_tag('&{};'.format(name), is_block=False)
- def handle_comment(self, data):
+ def handle_comment(self, data: str):
self.handle_empty_tag('<!--{}-->'.format(data), is_block=True)
- def handle_decl(self, data):
+ def handle_decl(self, data: str):
self.handle_empty_tag('<!{}>'.format(data), is_block=True)
- def handle_pi(self, data):
+ def handle_pi(self, data: str):
self.handle_empty_tag('<?{}?>'.format(data), is_block=True)
- def unknown_decl(self, data):
+ def unknown_decl(self, data: str):
end = ']]>' if data.startswith('CDATA[') else ']>'
self.handle_empty_tag('<![{}{}'.format(data, end), is_block=True)
- def parse_pi(self, i):
+ def parse_pi(self, i: int) -> int:
if self.at_line_start() or self.intail:
return super().parse_pi(i)
# This is not the beginning of a raw block so treat as plain data
self.handle_data('<?')
return i + 2
- def parse_html_declaration(self, i):
+ def parse_html_declaration(self, i: int) -> int:
if self.at_line_start() or self.intail:
return super().parse_html_declaration(i)
# This is not the beginning of a raw block so treat as plain data
return i + 2
# The rest has been copied from base class in standard lib to address #1036.
- # As __startag_text is private, all references to it must be in this subclass.
- # The last few lines of parse_starttag are reversed so that handle_starttag
- # can override cdata_mode in certain situations (in a code span).
- __starttag_text = None
+ # As `__startag_text` is private, all references to it must be in this subclass.
+ # The last few lines of `parse_starttag` are reversed so that `handle_starttag`
+ # can override `cdata_mode` in certain situations (in a code span).
+ __starttag_text: str | None = None
- def get_starttag_text(self):
- """Return full source of start tag: '<...>'."""
+ def get_starttag_text(self) -> str:
+ """Return full source of start tag: `<...>`."""
return self.__starttag_text
- def parse_starttag(self, i): # pragma: no cover
+ def parse_starttag(self, i: int) -> int: # pragma: no cover
self.__starttag_text = None
endpos = self.check_for_whole_start_tag(i)
if endpos < 0:
rawdata = self.rawdata
self.__starttag_text = rawdata[i:endpos]
- # Now parse the data between i+1 and j into a tag and attrs
+ # Now parse the data between `i+1` and `j` into a tag and `attrs`
attrs = []
match = htmlparser.tagfind_tolerant.match(rawdata, i+1)
assert match, 'unexpected call to parse_starttag()'
self.handle_data(rawdata[i:endpos])
return endpos
if end.endswith('/>'):
- # XHTML-style empty tag: <span attr="value" />
+ # XHTML-style empty tag: `<span attr="value" />`
self.handle_startendtag(tag, attrs)
else:
- # *** set cdata_mode first so we can override it in handle_starttag (see #1036) ***
+ # *** set `cdata_mode` first so we can override it in `handle_starttag` (see #1036) ***
if tag in self.CDATA_CONTENT_ELEMENTS:
self.set_cdata_mode(tag)
self.handle_starttag(tag, attrs)
-"""
-Python Markdown
-
-A Python implementation of John Gruber's Markdown.
-
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
-
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# Python Markdown
-License: BSD (see LICENSE.md for details).
+# A Python implementation of John Gruber's Markdown.
-INLINE PATTERNS
-=============================================================================
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Inline patterns such as *emphasis* are handled by means of auxiliary
-objects, one per pattern. Pattern objects must be instances of classes
-that extend markdown.Pattern. Each pattern object uses a single regular
-expression and needs support the following methods:
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
- pattern.getCompiledRegExp() # returns a regular expression
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
- pattern.handleMatch(m) # takes a match object and returns
- # an ElementTree element or just plain text
+# License: BSD (see LICENSE.md for details).
-All of python markdown's built-in patterns subclass from Pattern,
-but you can add additional patterns that don't.
-
-Also note that all the regular expressions used by inline must
-capture the whole block. For this reason, they all start with
-'^(.*)' and end with '(.*)!'. In case with built-in expression
-Pattern takes care of adding the "^(.*)" and "(.*)!".
-
-Finally, the order in which regular expressions are applied is very
-important - e.g. if we first replace http://.../ links with <a> tags
-and _then_ try to replace inline html, we would end up with a mess.
-So, we apply the expressions in the following order:
-
-* escape and backticks have to go before everything else, so
- that we can preempt any markdown patterns by escaping them.
+"""
+In version 3.0, a new, more flexible inline processor was added, [`markdown.inlinepatterns.InlineProcessor`][]. The
+original inline patterns, which inherit from [`markdown.inlinepatterns.Pattern`][] or one of its children are still
+supported, though users are encouraged to migrate.
-* then we handle auto-links (must be done before inline html)
+The new `InlineProcessor` provides two major enhancements to `Patterns`:
-* then we handle inline HTML. At this point we will simply
- replace all inline HTML strings with a placeholder and add
- the actual HTML to a hash.
+1. Inline Processors no longer need to match the entire block, so regular expressions no longer need to start with
+ `r'^(.*?)'` and end with `r'(.*?)%'`. This runs faster. The returned [`Match`][re.Match] object will only contain
+ what is explicitly matched in the pattern, and extension pattern groups now start with `m.group(1)`.
-* then inline images (must be done before links)
+2. The `handleMatch` method now takes an additional input called `data`, which is the entire block under analysis,
+ not just what is matched with the specified pattern. The method now returns the element *and* the indexes relative
+ to `data` that the return element is replacing (usually `m.start(0)` and `m.end(0)`). If the boundaries are
+ returned as `None`, it is assumed that the match did not take place, and nothing will be altered in `data`.
-* then bracketed links, first regular then reference-style
+ This allows handling of more complex constructs than regular expressions can handle, e.g., matching nested
+ brackets, and explicit control of the span "consumed" by the processor.
-* finally we apply strong and emphasis
"""
+from __future__ import annotations
+
from . import util
-from collections import namedtuple
+from typing import TYPE_CHECKING, Any, Collection, NamedTuple
import re
import xml.etree.ElementTree as etree
try: # pragma: no cover
except ImportError: # pragma: no cover
import htmlentitydefs as entities
+if TYPE_CHECKING: # pragma: no cover
+ from markdown import Markdown
-def build_inlinepatterns(md, **kwargs):
- """ Build the default set of inline patterns for Markdown. """
+
+def build_inlinepatterns(md: Markdown, **kwargs: Any) -> util.Registry[InlineProcessor]:
+ """
+ Build the default set of inline patterns for Markdown.
+
+ The order in which processors and/or patterns are applied is very important - e.g. if we first replace
+ `http://.../` links with `<a>` tags and _then_ try to replace inline HTML, we would end up with a mess. So, we
+ apply the expressions in the following order:
+
+ * backticks and escaped characters have to be handled before everything else so that we can preempt any markdown
+ patterns by escaping them;
+
+ * then we handle the various types of links (auto-links must be handled before inline HTML);
+
+ * then we handle inline HTML. At this point we will simply replace all inline HTML strings with a placeholder
+ and add the actual HTML to a stash;
+
+ * finally we apply strong, emphasis, etc.
+
+ """
inlinePatterns = util.Registry()
inlinePatterns.register(BacktickInlineProcessor(BACKTICK_RE), 'backtick', 190)
inlinePatterns.register(EscapeInlineProcessor(ESCAPE_RE, md), 'escape', 180)
return inlinePatterns
-"""
-The actual regular expressions for patterns
------------------------------------------------------------------------------
-"""
+# The actual regular expressions for patterns
+# -----------------------------------------------------------------------------
NOIMG = r'(?<!\!)'
+""" Match not an image. Partial regular expression which matches if not preceded by `!`. """
-# `e=f()` or ``e=f("`")``
BACKTICK_RE = r'(?:(?<!\\)((?:\\{2})+)(?=`+)|(?<!\\)(`+)(.+?)(?<!`)\2(?!`))'
+""" Match backtick quoted string (`` `e=f()` `` or ``` ``e=f("`")`` ```). """
-# \<
ESCAPE_RE = r'\\(.)'
+""" Match a backslash escaped character (`\\<` or `\\*`). """
-# *emphasis*
EMPHASIS_RE = r'(\*)([^\*]+)\1'
+""" Match emphasis with an asterisk (`*emphasis*`). """
-# **strong**
STRONG_RE = r'(\*{2})(.+?)\1'
+""" Match strong with an asterisk (`**strong**`). """
-# __smart__strong__
SMART_STRONG_RE = r'(?<!\w)(_{2})(?!_)(.+?)(?<!_)\1(?!\w)'
+""" Match strong with underscore while ignoring middle word underscores (`__smart__strong__`). """
-# _smart_emphasis_
SMART_EMPHASIS_RE = r'(?<!\w)(_)(?!_)(.+?)(?<!_)\1(?!\w)'
+""" Match emphasis with underscore while ignoring middle word underscores (`_smart_emphasis_`). """
-# __strong _em__
SMART_STRONG_EM_RE = r'(?<!\w)(\_)\1(?!\1)(.+?)(?<!\w)\1(?!\1)(.+?)\1{3}(?!\w)'
+""" Match strong emphasis with underscores (`__strong _em__`). """
-# ***strongem*** or ***em*strong**
EM_STRONG_RE = r'(\*)\1{2}(.+?)\1(.*?)\1{2}'
+""" Match emphasis strong with asterisk (`***strongem***` or `***em*strong**`). """
-# ___strongem___ or ___em_strong__
EM_STRONG2_RE = r'(_)\1{2}(.+?)\1(.*?)\1{2}'
+""" Match emphasis strong with underscores (`___emstrong___` or `___em_strong__`). """
-# ***strong**em*
STRONG_EM_RE = r'(\*)\1{2}(.+?)\1{2}(.*?)\1'
+""" Match strong emphasis with asterisk (`***strong**em*`). """
-# ___strong__em_
STRONG_EM2_RE = r'(_)\1{2}(.+?)\1{2}(.*?)\1'
+""" Match strong emphasis with underscores (`___strong__em_`). """
-# **strong*em***
STRONG_EM3_RE = r'(\*)\1(?!\1)([^*]+?)\1(?!\1)(.+?)\1{3}'
+""" Match strong emphasis with asterisk (`**strong*em***`). """
-# [text](url) or [text](<url>) or [text](url "title")
LINK_RE = NOIMG + r'\['
+""" Match start of in-line link (`[text](url)` or `[text](<url>)` or `[text](url "title")`). """
-#  or 
IMAGE_LINK_RE = r'\!\['
+""" Match start of in-line image link (`` or ``). """
-# [Google][3]
REFERENCE_RE = LINK_RE
+""" Match start of reference link (`[Label][3]`). """
-# ![alt text][2]
IMAGE_REFERENCE_RE = IMAGE_LINK_RE
+""" Match start of image reference (`![alt text][2]`). """
-# stand-alone * or _
-NOT_STRONG_RE = r'((^|\s)(\*|_)(\s|$))'
+NOT_STRONG_RE = r'((^|(?<=\s))(\*{1,3}|_{1,3})(?=\s|$))'
+""" Match a stand-alone `*` or `_`. """
-# <http://www.123.com>
AUTOLINK_RE = r'<((?:[Ff]|[Hh][Tt])[Tt][Pp][Ss]?://[^<>]*)>'
+""" Match an automatic link (`<http://www.example.com>`). """
-# <me@example.com>
AUTOMAIL_RE = r'<([^<> !]+@[^@<> ]+)>'
+""" Match an automatic email link (`<me@example.com>`). """
-# <...>
HTML_RE = r'(<(\/?[a-zA-Z][^<>@ ]*( [^<>]*)?|!--(?:(?!<!--|-->).)*--)>)'
+""" Match an HTML tag (`<...>`). """
-# "&" (decimal) or "&" (hex) or "&" (named)
ENTITY_RE = r'(&(?:\#[0-9]+|\#x[0-9a-fA-F]+|[a-zA-Z0-9]+);)'
+""" Match an HTML entity (`&` (decimal) or `&` (hex) or `&` (named)). """
-# two spaces at end of line
LINE_BREAK_RE = r' \n'
+""" Match two spaces at end of line. """
-def dequote(string):
+def dequote(string: str) -> str:
"""Remove quotes from around a string."""
if ((string.startswith('"') and string.endswith('"')) or
(string.startswith("'") and string.endswith("'"))):
return string
-class EmStrongItem(namedtuple('EmStrongItem', ['pattern', 'builder', 'tags'])):
+class EmStrongItem(NamedTuple):
"""Emphasis/strong pattern item."""
+ pattern: re.Pattern[str]
+ builder: str
+ tags: str
-"""
-The pattern classes
------------------------------------------------------------------------------
-"""
+# The pattern classes
+# -----------------------------------------------------------------------------
class Pattern: # pragma: no cover
- """Base class that inline patterns subclass. """
+ """
+ Base class that inline patterns subclass.
+
+ Inline patterns are handled by means of `Pattern` subclasses, one per regular expression.
+ Each pattern object uses a single regular expression and must support the following methods:
+ [`getCompiledRegExp`][markdown.inlinepatterns.Pattern.getCompiledRegExp] and
+ [`handleMatch`][markdown.inlinepatterns.Pattern.handleMatch].
+
+ All the regular expressions used by `Pattern` subclasses must capture the whole block. For this
+ reason, they all start with `^(.*)` and end with `(.*)!`. When passing a regular expression on
+ class initialization, the `^(.*)` and `(.*)!` are added automatically and the regular expression
+ is pre-compiled.
- ANCESTOR_EXCLUDES = tuple()
+ It is strongly suggested that the newer style [`markdown.inlinepatterns.InlineProcessor`][] that
+ use a more efficient and flexible search approach be used instead. However, the older style
+ `Pattern` remains for backward compatibility with many existing third-party extensions.
+
+ """
- def __init__(self, pattern, md=None):
+ ANCESTOR_EXCLUDES: Collection[str] = tuple()
+ """
+ A collection of elements which are undesirable ancestors. The processor will be skipped if it
+ would cause the content to be a descendant of one of the listed tag names.
+ """
+
+ def __init__(self, pattern: str, md: Markdown | None = None):
"""
Create an instant of an inline pattern.
- Keyword arguments:
+ Arguments:
+ pattern: A regular expression that matches a pattern.
+ md: An optional pointer to the instance of `markdown.Markdown` and is available as
+ `self.md` on the class instance.
- * pattern: A regular expression that matches a pattern
"""
self.pattern = pattern
self.md = md
- @property
- @util.deprecated("Use 'md' instead.")
- def markdown(self):
- # TODO: remove this later
- return self.md
-
- def getCompiledRegExp(self):
+ def getCompiledRegExp(self) -> re.Pattern:
""" Return a compiled regular expression. """
return self.compiled_re
- def handleMatch(self, m):
+ def handleMatch(self, m: re.Match[str]) -> etree.Element | str:
"""Return a ElementTree element from the given match.
Subclasses should override this method.
- Keyword arguments:
+ Arguments:
+ m: A match object containing a match of the pattern.
- * m: A re match object containing a match of the pattern.
+ Returns: An ElementTree Element object.
"""
pass # pragma: no cover
- def type(self):
+ def type(self) -> str:
""" Return class name, to define pattern type """
return self.__class__.__name__
- def unescape(self, text):
+ def unescape(self, text: str) -> str:
""" Return unescaped text given text with an inline placeholder. """
try:
stash = self.md.treeprocessors['inline'].stashed_nodes
if isinstance(value, str):
return value
else:
- # An etree Element - return text content only
+ # An `etree` Element - return text content only
return ''.join(value.itertext())
return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
class InlineProcessor(Pattern):
"""
- Base class that inline patterns subclass.
+ Base class that inline processors subclass.
This is the newer style inline processor that uses a more
efficient and flexible search approach.
+
"""
- def __init__(self, pattern, md=None):
+ def __init__(self, pattern: str, md: Markdown | None = None):
"""
- Create an instant of an inline pattern.
-
- Keyword arguments:
+ Create an instant of an inline processor.
- * pattern: A regular expression that matches a pattern
+ Arguments:
+ pattern: A regular expression that matches a pattern.
+ md: An optional pointer to the instance of `markdown.Markdown` and is available as
+ `self.md` on the class instance.
"""
self.pattern = pattern
self.compiled_re = re.compile(pattern, re.DOTALL | re.UNICODE)
- # Api for Markdown to pass safe_mode into instance
+ # API for Markdown to pass `safe_mode` into instance
self.safe_mode = False
self.md = md
- def handleMatch(self, m, data):
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | str | None, int | None, int | None]:
"""Return a ElementTree element from the given match and the
start and end index of the matched text.
Subclasses should override this method.
- Keyword arguments:
-
- * m: A re match object containing a match of the pattern.
- * data: The buffer current under analysis
+ Arguments:
+ m: A re match object containing a match of the pattern.
+ data: The buffer currently under analysis.
Returns:
-
- * el: The ElementTree element, text or None.
- * start: The start of the region that has been matched or None.
- * end: The end of the region that has been matched or None.
+ el: The ElementTree element, text or None.
+ start: The start of the region that has been matched or None.
+ end: The end of the region that has been matched or None.
"""
pass # pragma: no cover
class SimpleTextPattern(Pattern): # pragma: no cover
- """ Return a simple text of group(2) of a Pattern. """
- def handleMatch(self, m):
+ """ Return a simple text of `group(2)` of a Pattern. """
+ def handleMatch(self, m: re.Match[str]) -> str:
+ """ Return string content of `group(2)` of a matching pattern. """
return m.group(2)
class SimpleTextInlineProcessor(InlineProcessor):
- """ Return a simple text of group(1) of a Pattern. """
- def handleMatch(self, m, data):
+ """ Return a simple text of `group(1)` of a Pattern. """
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[str, int, int]:
+ """ Return string content of `group(1)` of a matching pattern. """
return m.group(1), m.start(0), m.end(0)
class EscapeInlineProcessor(InlineProcessor):
""" Return an escaped character. """
- def handleMatch(self, m, data):
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[str | None, int, int]:
+ """
+ If the character matched by `group(1)` of a pattern is in [`ESCAPED_CHARS`][markdown.Markdown.ESCAPED_CHARS]
+ then return the integer representing the character's Unicode code point (as returned by [`ord`][]) wrapped
+ in [`util.STX`][markdown.util.STX] and [`util.ETX`][markdown.util.ETX].
+
+ If the matched character is not in [`ESCAPED_CHARS`][markdown.Markdown.ESCAPED_CHARS], then return `None`.
+ """
+
char = m.group(1)
if char in self.md.ESCAPED_CHARS:
return '{}{}{}'.format(util.STX, ord(char), util.ETX), m.start(0), m.end(0)
class SimpleTagPattern(Pattern): # pragma: no cover
"""
- Return element of type `tag` with a text attribute of group(3)
+ Return element of type `tag` with a text attribute of `group(3)`
of a Pattern.
"""
- def __init__(self, pattern, tag):
+ def __init__(self, pattern: str, tag: str):
+ """
+ Create an instant of an simple tag pattern.
+
+ Arguments:
+ pattern: A regular expression that matches a pattern.
+ tag: Tag of element.
+
+ """
Pattern.__init__(self, pattern)
self.tag = tag
+ """ The tag of the rendered element. """
- def handleMatch(self, m):
+ def handleMatch(self, m: re.Match[str]) -> etree.Element:
+ """
+ Return [`Element`][xml.etree.ElementTree.Element] of type `tag` with the string in `group(3)` of a
+ matching pattern as the Element's text.
+ """
el = etree.Element(self.tag)
el.text = m.group(3)
return el
class SimpleTagInlineProcessor(InlineProcessor):
"""
- Return element of type `tag` with a text attribute of group(2)
+ Return element of type `tag` with a text attribute of `group(2)`
of a Pattern.
"""
- def __init__(self, pattern, tag):
+ def __init__(self, pattern: str, tag: str):
+ """
+ Create an instant of an simple tag processor.
+
+ Arguments:
+ pattern: A regular expression that matches a pattern.
+ tag: Tag of element.
+
+ """
InlineProcessor.__init__(self, pattern)
self.tag = tag
+ """ The tag of the rendered element. """
- def handleMatch(self, m, data): # pragma: no cover
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element, int, int]: # pragma: no cover
+ """
+ Return [`Element`][xml.etree.ElementTree.Element] of type `tag` with the string in `group(2)` of a
+ matching pattern as the Element's text.
+ """
el = etree.Element(self.tag)
el.text = m.group(2)
return el, m.start(0), m.end(0)
class SubstituteTagPattern(SimpleTagPattern): # pragma: no cover
""" Return an element of type `tag` with no children. """
- def handleMatch(self, m):
+ def handleMatch(self, m: re.Match[str]) -> etree.Element:
+ """ Return empty [`Element`][xml.etree.ElementTree.Element] of type `tag`. """
return etree.Element(self.tag)
class SubstituteTagInlineProcessor(SimpleTagInlineProcessor):
""" Return an element of type `tag` with no children. """
- def handleMatch(self, m, data):
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element, int, int]:
+ """ Return empty [`Element`][xml.etree.ElementTree.Element] of type `tag`. """
return etree.Element(self.tag), m.start(0), m.end(0)
class BacktickInlineProcessor(InlineProcessor):
- """ Return a `<code>` element containing the matching text. """
+ """ Return a `<code>` element containing the escaped matching text. """
def __init__(self, pattern):
InlineProcessor.__init__(self, pattern)
self.ESCAPED_BSLASH = '{}{}{}'.format(util.STX, ord('\\'), util.ETX)
self.tag = 'code'
+ """ The tag of the rendered element. """
- def handleMatch(self, m, data):
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | str, int, int]:
+ """
+ If the match contains `group(3)` of a pattern, then return a `code`
+ [`Element`][xml.etree.ElementTree.Element] which contains HTML escaped text (with
+ [`code_escape`][markdown.util.code_escape]) as an [`AtomicString`][markdown.util.AtomicString].
+
+ If the match does not contain `group(3)` then return the text of `group(1)` backslash escaped.
+
+ """
if m.group(3):
el = etree.Element(self.tag)
el.text = util.AtomicString(util.code_escape(m.group(3).strip()))
Useful for strong emphasis etc.
"""
- def handleMatch(self, m):
+ def handleMatch(self, m: re.Match[str]) -> etree.Element:
+ """
+ Return [`Element`][xml.etree.ElementTree.Element] in following format:
+ `<tag1><tag2>group(3)</tag2>group(4)</tag2>` where `group(4)` is optional.
+
+ """
tag1, tag2 = self.tag.split(",")
el1 = etree.Element(tag1)
el2 = etree.SubElement(el1, tag2)
Useful for strong emphasis etc.
"""
- def handleMatch(self, m, data): # pragma: no cover
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element, int, int]: # pragma: no cover
+ """
+ Return [`Element`][xml.etree.ElementTree.Element] in following format:
+ `<tag1><tag2>group(2)</tag2>group(3)</tag2>` where `group(3)` is optional.
+
+ """
tag1, tag2 = self.tag.split(",")
el1 = etree.Element(tag1)
el2 = etree.SubElement(el1, tag2)
class HtmlInlineProcessor(InlineProcessor):
""" Store raw inline html and return a placeholder. """
- def handleMatch(self, m, data):
- rawhtml = self.unescape(m.group(1))
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[str, int, int]:
+ """ Store the text of `group(1)` of a pattern and return a placeholder string. """
+ rawhtml = self.backslash_unescape(self.unescape(m.group(1)))
place_holder = self.md.htmlStash.store(rawhtml)
return place_holder, m.start(0), m.end(0)
return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
+ def backslash_unescape(self, text):
+ """ Return text with backslash escapes undone (backslashes are restored). """
+ try:
+ RE = self.md.treeprocessors['unescape'].RE
+ except KeyError: # pragma: no cover
+ return text
+
+ def _unescape(m):
+ return chr(int(m.group(1)))
+
+ return RE.sub(_unescape, text)
+
class AsteriskProcessor(InlineProcessor):
"""Emphasis processor for handling strong and em matches inside asterisks."""
EmStrongItem(re.compile(STRONG_RE, re.DOTALL | re.UNICODE), 'single', 'strong'),
EmStrongItem(re.compile(EMPHASIS_RE, re.DOTALL | re.UNICODE), 'single', 'em')
]
+ """ The various strong and emphasis patterns handled by this processor. """
def build_single(self, m, tag, idx):
"""Return single tag."""
self.parse_sub_patterns(text, el2, None, idx)
return el1
- def parse_sub_patterns(self, data, parent, last, idx):
+ def parse_sub_patterns(self, data, parent, last, idx) -> None:
"""
Parses sub patterns.
else:
return self.build_single(m, tags, index)
- def handleMatch(self, m, data):
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | None, int | None, int | None]:
"""Parse patterns."""
el = None
EmStrongItem(re.compile(SMART_STRONG_RE, re.DOTALL | re.UNICODE), 'single', 'strong'),
EmStrongItem(re.compile(SMART_EMPHASIS_RE, re.DOTALL | re.UNICODE), 'single', 'em')
]
+ """ The various strong and emphasis patterns handled by this processor. """
class LinkInlineProcessor(InlineProcessor):
RE_LINK = re.compile(r'''\(\s*(?:(<[^<>]*>)\s*(?:('[^']*'|"[^"]*")\s*)?\))?''', re.DOTALL | re.UNICODE)
RE_TITLE_CLEAN = re.compile(r'\s')
- def handleMatch(self, m, data):
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | None, int | None, int | None]:
+ """ Return an `a` [`Element`][xml.etree.ElementTree.Element] or `(None, None, None)`. """
text, index, handled = self.getText(data, m.end(0))
if not handled:
if c != ' ':
last = c
- # We have a scenario: [test](link"notitle)
+ # We have a scenario: `[test](link"notitle)`
# When we enter a string, we stop tracking bracket resolution in the main counter,
# but we do keep a backup counter up until we discover where we might resolve all brackets
# if the title string fails to resolve.
class ImageInlineProcessor(LinkInlineProcessor):
- """ Return a img element from the given match. """
+ """ Return a `img` element from the given match. """
- def handleMatch(self, m, data):
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | None, int | None, int | None]:
+ """ Return an `img` [`Element`][xml.etree.ElementTree.Element] or `(None, None, None)`. """
text, index, handled = self.getText(data, m.end(0))
if not handled:
return None, None, None
RE_LINK = re.compile(r'\s?\[([^\]]*)\]', re.DOTALL | re.UNICODE)
- def handleMatch(self, m, data):
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | None, int | None, int | None]:
+ """
+ Return [`Element`][xml.etree.ElementTree.Element] returned by `makeTag` method or `(None, None, None)`.
+
+ """
text, index, handled = self.getText(data, m.end(0))
if not handled:
return None, None, None
if not handled:
return None, None, None
- # Clean up linebreaks in id
+ # Clean up line breaks in id
id = self.NEWLINE_CLEANUP_RE.sub(' ', id)
if id not in self.md.references: # ignore undefined refs
return None, m.start(0), end
def evalId(self, data, index, text):
"""
- Evaluate the id portion of [ref][id].
+ Evaluate the id portion of `[ref][id]`.
- If [ref][] use [ref].
+ If `[ref][]` use `[ref]`.
"""
m = self.RE_LINK.match(data, pos=index)
if not m:
id = text.lower()
return id, end, True
- def makeTag(self, href, title, text):
+ def makeTag(self, href: str, title: str, text: str) -> etree.Element:
+ """ Return an `a` [`Element`][xml.etree.ElementTree.Element]. """
el = etree.Element('a')
el.set('href', href)
class ShortReferenceInlineProcessor(ReferenceInlineProcessor):
- """Short form of reference: [google]. """
+ """Short form of reference: `[google]`. """
def evalId(self, data, index, text):
- """Evaluate the id from of [ref] """
+ """Evaluate the id of `[ref]`. """
return text.lower(), index, True
class ImageReferenceInlineProcessor(ReferenceInlineProcessor):
- """ Match to a stored reference and return img element. """
- def makeTag(self, href, title, text):
+ """ Match to a stored reference and return `img` element. """
+ def makeTag(self, href: str, title: str, text: str) -> etree.Element:
+ """ Return an `img` [`Element`][xml.etree.ElementTree.Element]. """
el = etree.Element("img")
el.set("src", href)
if title:
class ShortImageReferenceInlineProcessor(ImageReferenceInlineProcessor):
- """ Short form of inage reference: ![ref]. """
+ """ Short form of image reference: `![ref]`. """
def evalId(self, data, index, text):
- """Evaluate the id from of [ref] """
+ """Evaluate the id of `[ref]`. """
return text.lower(), index, True
class AutolinkInlineProcessor(InlineProcessor):
- """ Return a link Element given an autolink (`<http://example/com>`). """
- def handleMatch(self, m, data):
+ """ Return a link Element given an auto-link (`<http://example/com>`). """
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element, int, int]:
+ """ Return an `a` [`Element`][xml.etree.ElementTree.Element] of `group(1)`. """
el = etree.Element("a")
el.set('href', self.unescape(m.group(1)))
el.text = util.AtomicString(m.group(1))
class AutomailInlineProcessor(InlineProcessor):
"""
- Return a mailto link Element given an automail link (`<foo@example.com>`).
+ Return a `mailto` link Element given an auto-mail link (`<foo@example.com>`).
"""
- def handleMatch(self, m, data):
+ def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element, int, int]:
+ """ Return an [`Element`][xml.etree.ElementTree.Element] containing a `mailto` link of `group(1)`. """
el = etree.Element('a')
email = self.unescape(m.group(1))
if email.startswith("mailto:"):
+++ /dev/null
-"""
-Backport of PEP 562.
-
-https://pypi.org/search/?q=pep562
-
-Licensed under MIT
-Copyright (c) 2018 Isaac Muse <isaacmuse@gmail.com>
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
-documentation files (the "Software"), to deal in the Software without restriction, including without limitation
-the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
-and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions
-of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
-TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
-THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
-CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-IN THE SOFTWARE.
-"""
-import sys
-from collections import namedtuple
-import re
-
-__all__ = ('Pep562',)
-
-RE_VER = re.compile(
- r'''(?x)
- (?P<major>\d+)(?:\.(?P<minor>\d+))?(?:\.(?P<micro>\d+))?
- (?:(?P<type>a|b|rc)(?P<pre>\d+))?
- (?:\.post(?P<post>\d+))?
- (?:\.dev(?P<dev>\d+))?
- '''
-)
-
-REL_MAP = {
- ".dev": "",
- ".dev-alpha": "a",
- ".dev-beta": "b",
- ".dev-candidate": "rc",
- "alpha": "a",
- "beta": "b",
- "candidate": "rc",
- "final": ""
-}
-
-DEV_STATUS = {
- ".dev": "2 - Pre-Alpha",
- ".dev-alpha": "2 - Pre-Alpha",
- ".dev-beta": "2 - Pre-Alpha",
- ".dev-candidate": "2 - Pre-Alpha",
- "alpha": "3 - Alpha",
- "beta": "4 - Beta",
- "candidate": "4 - Beta",
- "final": "5 - Production/Stable"
-}
-
-PRE_REL_MAP = {"a": 'alpha', "b": 'beta', "rc": 'candidate'}
-
-
-class Version(namedtuple("Version", ["major", "minor", "micro", "release", "pre", "post", "dev"])):
- """
- Get the version (PEP 440).
-
- A biased approach to the PEP 440 semantic version.
-
- Provides a tuple structure which is sorted for comparisons `v1 > v2` etc.
- (major, minor, micro, release type, pre-release build, post-release build, development release build)
- Release types are named in is such a way they are comparable with ease.
- Accessors to check if a development, pre-release, or post-release build. Also provides accessor to get
- development status for setup files.
-
- How it works (currently):
-
- - You must specify a release type as either `final`, `alpha`, `beta`, or `candidate`.
- - To define a development release, you can use either `.dev`, `.dev-alpha`, `.dev-beta`, or `.dev-candidate`.
- The dot is used to ensure all development specifiers are sorted before `alpha`.
- You can specify a `dev` number for development builds, but do not have to as implicit development releases
- are allowed.
- - You must specify a `pre` value greater than zero if using a prerelease as this project (not PEP 440) does not
- allow implicit prereleases.
- - You can optionally set `post` to a value greater than zero to make the build a post release. While post releases
- are technically allowed in prereleases, it is strongly discouraged, so we are rejecting them. It should be
- noted that we do not allow `post0` even though PEP 440 does not restrict this. This project specifically
- does not allow implicit post releases.
- - It should be noted that we do not support epochs `1!` or local versions `+some-custom.version-1`.
-
- Acceptable version releases:
-
- ```
- Version(1, 0, 0, "final") 1.0
- Version(1, 2, 0, "final") 1.2
- Version(1, 2, 3, "final") 1.2.3
- Version(1, 2, 0, ".dev-alpha", pre=4) 1.2a4
- Version(1, 2, 0, ".dev-beta", pre=4) 1.2b4
- Version(1, 2, 0, ".dev-candidate", pre=4) 1.2rc4
- Version(1, 2, 0, "final", post=1) 1.2.post1
- Version(1, 2, 3, ".dev") 1.2.3.dev0
- Version(1, 2, 3, ".dev", dev=1) 1.2.3.dev1
- ```
-
- """
-
- def __new__(cls, major, minor, micro, release="final", pre=0, post=0, dev=0):
- """Validate version info."""
-
- # Ensure all parts are positive integers.
- for value in (major, minor, micro, pre, post):
- if not (isinstance(value, int) and value >= 0):
- raise ValueError("All version parts except 'release' should be integers.")
-
- if release not in REL_MAP:
- raise ValueError("'{}' is not a valid release type.".format(release))
-
- # Ensure valid pre-release (we do not allow implicit pre-releases).
- if ".dev-candidate" < release < "final":
- if pre == 0:
- raise ValueError("Implicit pre-releases not allowed.")
- elif dev:
- raise ValueError("Version is not a development release.")
- elif post:
- raise ValueError("Post-releases are not allowed with pre-releases.")
-
- # Ensure valid development or development/pre release
- elif release < "alpha":
- if release > ".dev" and pre == 0:
- raise ValueError("Implicit pre-release not allowed.")
- elif post:
- raise ValueError("Post-releases are not allowed with pre-releases.")
-
- # Ensure a valid normal release
- else:
- if pre:
- raise ValueError("Version is not a pre-release.")
- elif dev:
- raise ValueError("Version is not a development release.")
-
- return super().__new__(cls, major, minor, micro, release, pre, post, dev)
-
- def _is_pre(self):
- """Is prerelease."""
-
- return self.pre > 0
-
- def _is_dev(self):
- """Is development."""
-
- return bool(self.release < "alpha")
-
- def _is_post(self):
- """Is post."""
-
- return self.post > 0
-
- def _get_dev_status(self): # pragma: no cover
- """Get development status string."""
-
- return DEV_STATUS[self.release]
-
- def _get_canonical(self):
- """Get the canonical output string."""
-
- # Assemble major, minor, micro version and append `pre`, `post`, or `dev` if needed..
- if self.micro == 0:
- ver = "{}.{}".format(self.major, self.minor)
- else:
- ver = "{}.{}.{}".format(self.major, self.minor, self.micro)
- if self._is_pre():
- ver += '{}{}'.format(REL_MAP[self.release], self.pre)
- if self._is_post():
- ver += ".post{}".format(self.post)
- if self._is_dev():
- ver += ".dev{}".format(self.dev)
-
- return ver
-
-
-def parse_version(ver, pre=False):
- """Parse version into a comparable Version tuple."""
-
- m = RE_VER.match(ver)
-
- # Handle major, minor, micro
- major = int(m.group('major'))
- minor = int(m.group('minor')) if m.group('minor') else 0
- micro = int(m.group('micro')) if m.group('micro') else 0
-
- # Handle pre releases
- if m.group('type'):
- release = PRE_REL_MAP[m.group('type')]
- pre = int(m.group('pre'))
- else:
- release = "final"
- pre = 0
-
- # Handle development releases
- dev = m.group('dev') if m.group('dev') else 0
- if m.group('dev'):
- dev = int(m.group('dev'))
- release = '.dev-' + release if pre else '.dev'
- else:
- dev = 0
-
- # Handle post
- post = int(m.group('post')) if m.group('post') else 0
-
- return Version(major, minor, micro, release, pre, post, dev)
-
-
-class Pep562:
- """
- Backport of PEP 562 <https://pypi.org/search/?q=pep562>.
-
- Wraps the module in a class that exposes the mechanics to override `__dir__` and `__getattr__`.
- The given module will be searched for overrides of `__dir__` and `__getattr__` and use them when needed.
- """
-
- def __init__(self, name):
- """Acquire `__getattr__` and `__dir__`, but only replace module for versions less than Python 3.7."""
-
- self._module = sys.modules[name]
- self._get_attr = getattr(self._module, '__getattr__', None)
- self._get_dir = getattr(self._module, '__dir__', None)
- sys.modules[name] = self
-
- def __dir__(self):
- """Return the overridden `dir` if one was provided, else apply `dir` to the module."""
-
- return self._get_dir() if self._get_dir else dir(self._module)
-
- def __getattr__(self, name):
- """Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present."""
-
- try:
- return getattr(self._module, name)
- except AttributeError:
- if self._get_attr:
- return self._get_attr(name)
- raise
-
-
-__version_info__ = Version(1, 0, 0, "final")
-__version__ = __version_info__._get_canonical()
-"""
-Python Markdown
+# Python Markdown
-A Python implementation of John Gruber's Markdown.
+# A Python implementation of John Gruber's Markdown.
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
-License: BSD (see LICENSE.md for details).
+# License: BSD (see LICENSE.md for details).
-POST-PROCESSORS
-=============================================================================
+"""
-Markdown also allows post-processors, which are similar to preprocessors in
-that they need to implement a "run" method. However, they are run after core
-processing.
+Post-processors run on the text of the entire document after is has been serialized into a string.
+Postprocessors should be used to work with the text just before output. Usually, they are used add
+back sections that were extracted in a preprocessor, fix up outgoing encodings, or wrap the whole
+document.
"""
+from __future__ import annotations
+
from collections import OrderedDict
+from typing import TYPE_CHECKING, Any
from . import util
import re
+if TYPE_CHECKING: # pragma: no cover
+ from markdown import Markdown
-def build_postprocessors(md, **kwargs):
+
+def build_postprocessors(md: Markdown, **kwargs: Any) -> util.Registry[Postprocessor]:
""" Build the default postprocessors for Markdown. """
postprocessors = util.Registry()
postprocessors.register(RawHtmlPostprocessor(md), 'raw_html', 30)
postprocessors.register(AndSubstitutePostprocessor(), 'amp_substitute', 20)
- postprocessors.register(UnescapePostprocessor(), 'unescape', 10)
return postprocessors
"""
Postprocessors are run after the ElementTree it converted back into text.
- Each Postprocessor implements a "run" method that takes a pointer to a
+ Each Postprocessor implements a `run` method that takes a pointer to a
text string, modifies it as necessary and returns a text string.
- Postprocessors must extend markdown.Postprocessor.
+ Postprocessors must extend `Postprocessor`.
"""
- def run(self, text):
+ def run(self, text: str) -> str:
"""
- Subclasses of Postprocessor should implement a `run` method, which
+ Subclasses of `Postprocessor` should implement a `run` method, which
takes the html document as a single text string and returns a
(possibly modified) string.
BLOCK_LEVEL_REGEX = re.compile(r'^\<\/?([^ >]+)')
- def run(self, text):
+ def run(self, text: str):
""" Iterate over html stash and restore html. """
replacements = OrderedDict()
for i in range(self.md.htmlStash.html_counter):
else:
return self.run(processed_text)
- def isblocklevel(self, html):
+ def isblocklevel(self, html: str) -> bool:
+ """ Check is block of HTML is block-level. """
m = self.BLOCK_LEVEL_REGEX.match(html)
if m:
if m.group(1)[0] in ('!', '?', '@', '%'):
- # Comment, php etc...
+ # Comment, PHP etc...
return True
return self.md.is_block_level(m.group(1))
return False
- def stash_to_string(self, text):
+ def stash_to_string(self, text: str) -> str:
""" Convert a stashed object to a string. """
return str(text)
return text
+@util.deprecated(
+ "This class is deprecated and will be removed in the future; "
+ "use [`UnescapeTreeprocessor`][markdown.treeprocessors.UnescapeTreeprocessor] instead."
+)
class UnescapePostprocessor(Postprocessor):
- """ Restore escaped chars """
+ """ Restore escaped chars. """
RE = re.compile(r'{}(\d+){}'.format(util.STX, util.ETX))
-"""
-Python Markdown
-
-A Python implementation of John Gruber's Markdown.
+# Python Markdown
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# A Python implementation of John Gruber's Markdown.
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-License: BSD (see LICENSE.md for details).
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
-PRE-PROCESSORS
-=============================================================================
+# License: BSD (see LICENSE.md for details).
-Preprocessors work on source text before we start doing anything too
-complicated.
"""
+Preprocessors work on source text before it is broken down into its individual parts.
+This is an excellent place to clean up bad characters or to extract portions for later
+processing that the parser may otherwise choke on.
+"""
+
+from __future__ import annotations
+from typing import TYPE_CHECKING, Any
from . import util
from .htmlparser import HTMLExtractor
import re
+if TYPE_CHECKING: # pragma: no cover
+ from markdown import Markdown
-def build_preprocessors(md, **kwargs):
- """ Build the default set of preprocessors used by Markdown. """
+
+def build_preprocessors(md: Markdown, **kwargs: Any) -> util.Registry[Preprocessor]:
+ """ Build and return the default set of preprocessors used by Markdown. """
preprocessors = util.Registry()
preprocessors.register(NormalizeWhitespace(md), 'normalize_whitespace', 30)
preprocessors.register(HtmlBlockPreprocessor(md), 'html_block', 20)
"""
Preprocessors are run after the text is broken into lines.
- Each preprocessor implements a "run" method that takes a pointer to a
+ Each preprocessor implements a `run` method that takes a pointer to a
list of lines of the document, modifies it as necessary and returns
either the same pointer or a pointer to a new list.
- Preprocessors must extend markdown.Preprocessor.
+ Preprocessors must extend `Preprocessor`.
"""
- def run(self, lines):
+ def run(self, lines: list[str]) -> list[str]:
"""
- Each subclass of Preprocessor should override the `run` method, which
+ Each subclass of `Preprocessor` should override the `run` method, which
takes the document as a list of strings split by newlines and returns
the (possibly modified) list of lines.
class NormalizeWhitespace(Preprocessor):
""" Normalize whitespace for consistent parsing. """
- def run(self, lines):
+ def run(self, lines: list[str]) -> list[str]:
source = '\n'.join(lines)
source = source.replace(util.STX, "").replace(util.ETX, "")
source = source.replace("\r\n", "\n").replace("\r", "\n") + "\n\n"
class HtmlBlockPreprocessor(Preprocessor):
- """Remove html blocks from the text and store them for later retrieval."""
+ """
+ Remove html blocks from the text and store them for later retrieval.
+
+ The raw HTML is stored in the [`htmlStash`][markdown.util.HtmlStash] of the
+ [`Markdown`][markdown.Markdown] instance.
+ """
- def run(self, lines):
+ def run(self, lines: list[str]) -> list[str]:
source = '\n'.join(lines)
parser = HTMLExtractor(self.md)
parser.feed(source)
-# markdown/searializers.py
-#
-# Add x/html serialization to Elementree
+# Add x/html serialization to `Elementree`
# Taken from ElementTree 1.3 preview with slight modifications
#
# Copyright (c) 1999-2007 by Fredrik Lundh. All rights reserved.
# OF THIS SOFTWARE.
# --------------------------------------------------------------------
+"""
+Python-Markdown provides two serializers which render [`ElementTree.Element`][xml.etree.ElementTree.Element]
+objects to a string of HTML. Both functions wrap the same underlying code with only a few minor
+differences as outlined below:
+
+1. Empty (self-closing) tags are rendered as `<tag>` for HTML and as `<tag />` for XHTML.
+2. Boolean attributes are rendered as `attrname` for HTML and as `attrname="attrname"` for XHTML.
+"""
+
+from __future__ import annotations
from xml.etree.ElementTree import ProcessingInstruction
-from xml.etree.ElementTree import Comment, ElementTree, QName
+from xml.etree.ElementTree import Comment, ElementTree, Element, QName, HTML_EMPTY
import re
__all__ = ['to_html_string', 'to_xhtml_string']
-HTML_EMPTY = ("area", "base", "basefont", "br", "col", "frame", "hr",
- "img", "input", "isindex", "link", "meta", "param")
RE_AMP = re.compile(r'&(?!(?:\#[0-9]+|\#x[0-9a-f]+|[0-9a-z]+);)', re.I)
-try:
- HTML_EMPTY = set(HTML_EMPTY)
-except NameError: # pragma: no cover
- pass
-
def _raise_serialization_error(text): # pragma: no cover
raise TypeError(
else:
namespace_uri = None
if isinstance(tag, QName):
- # QNAME objects store their data as a string: `{uri}tag`
+ # `QNAME` objects store their data as a string: `{uri}tag`
if tag.text[:1] == "{":
namespace_uri, tag = tag.text[1:].split("}", 1)
else:
items = sorted(items) # lexical order
for k, v in items:
if isinstance(k, QName):
- # Assume a text only QName
+ # Assume a text only `QName`
k = k.text
if isinstance(v, QName):
- # Assume a text only QName
+ # Assume a text only `QName`
v = v.text
else:
v = _escape_attrib_html(v)
# --------------------------------------------------------------------
# public functions
-def to_html_string(element):
+
+def to_html_string(element: Element) -> str:
+ """ Serialize element and its children to a string of HTML5. """
return _write_html(ElementTree(element).getroot(), format="html")
-def to_xhtml_string(element):
+def to_xhtml_string(element: Element) -> str:
+ """ Serialize element and its children to a string of XHTML. """
return _write_html(ElementTree(element).getroot(), format="xhtml")
-"""
-Python Markdown
+# Python Markdown
-A Python implementation of John Gruber's Markdown.
+# A Python implementation of John Gruber's Markdown.
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
-License: BSD (see LICENSE.md for details).
-"""
+# License: BSD (see LICENSE.md for details).
+
+""" A collection of tools for testing the Markdown code base and extensions. """
+
+from __future__ import annotations
import os
import sys
import unittest
import textwrap
+from typing import Any
from . import markdown, Markdown, util
try:
class TestCase(unittest.TestCase):
"""
- A unittest.TestCase subclass with helpers for testing Markdown output.
+ A [`unittest.TestCase`][] subclass with helpers for testing Markdown output.
- Define `default_kwargs` as a dict of keywords to pass to Markdown for each
+ Define `default_kwargs` as a `dict` of keywords to pass to Markdown for each
test. The defaults can be overridden on individual tests.
The `assertMarkdownRenders` method accepts the source text, the expected
output, and any keywords to pass to Markdown. The `default_kwargs` are used
except where overridden by `kwargs`. The output and expected output are passed
- to `TestCase.assertMultiLineEqual`. An AssertionError is raised with a diff
+ to `TestCase.assertMultiLineEqual`. An `AssertionError` is raised with a diff
if the actual output does not equal the expected output.
The `dedent` method is available to dedent triple-quoted strings if
necessary.
- In all other respects, behaves as unittest.TestCase.
+ In all other respects, behaves as `unittest.TestCase`.
"""
- default_kwargs = {}
+ default_kwargs: dict[str, Any] = {}
+ """ Default options to pass to Markdown for each test. """
def assertMarkdownRenders(self, source, expected, expected_attrs=None, **kwargs):
"""
Test that source Markdown text renders to expected output with given keywords.
- `expected_attrs` accepts a dict. Each key should be the name of an attribute
+ `expected_attrs` accepts a `dict`. Each key should be the name of an attribute
on the `Markdown` instance and the value should be the expected value after
the source text is parsed by Markdown. After the expected output is tested,
the expected value for each attribute is compared against the actual
"""
# TODO: If/when actual output ends with a newline, then use:
- # return textwrap.dedent(text.strip('/n'))
+ # return textwrap.dedent(text.strip('/n'))
return textwrap.dedent(text).strip()
Example usage:
- with recursionlimit(20):
- # test code here
+ ``` python
+ with recursionlimit(20):
+ # test code here
+ ```
- See https://stackoverflow.com/a/50120316/866026
+ See <https://stackoverflow.com/a/50120316/866026>.
"""
def __init__(self, limit):
class Kwargs(dict):
- """ A dict like class for holding keyword arguments. """
+ """ A `dict` like class for holding keyword arguments. """
pass
def _normalize_whitespace(text):
- """ Normalize whitespace for a string of html using tidylib. """
+ """ Normalize whitespace for a string of HTML using `tidylib`. """
output, errors = tidylib.tidy_fragment(text, options={
'drop_empty_paras': 0,
'fix_backslash': 0,
class LegacyTestCase(unittest.TestCase, metaclass=LegacyTestMeta):
"""
- A `unittest.TestCase` subclass for running Markdown's legacy file-based tests.
+ A [`unittest.TestCase`][] subclass for running Markdown's legacy file-based tests.
A subclass should define various properties which point to a directory of
text-based test files and define various behaviors/defaults for those tests.
The following properties are supported:
- location: A path to the directory of test files. An absolute path is preferred.
- exclude: A list of tests to exclude. Each test name should comprise the filename
- without an extension.
- normalize: A boolean value indicating if the HTML should be normalized.
- Default: `False`.
- input_ext: A string containing the file extension of input files. Default: `.txt`.
- ouput_ext: A string containing the file extension of expected output files.
- Default: `html`.
- default_kwargs: A `Kwargs` instance which stores the default set of keyword
- arguments for all test files in the directory.
+ Attributes:
+ location (str): A path to the directory of test files. An absolute path is preferred.
+ exclude (list[str]): A list of tests to exclude. Each test name should comprise the filename
+ without an extension.
+ normalize (bool): A boolean value indicating if the HTML should be normalized. Default: `False`.
+ input_ext (str): A string containing the file extension of input files. Default: `.txt`.
+ output_ext (str): A string containing the file extension of expected output files. Default: `html`.
+ default_kwargs (Kwargs[str, Any]): The default set of keyword arguments for all test files in the directory.
In addition, properties can be defined for each individual set of test files within
the directory. The property should be given the name of the file without the file
test file. The keyword arguments will "update" the `default_kwargs`.
When the class instance is created, it will walk the given directory and create
- a separate unitttest for each set of test files using the naming scheme:
- `test_filename`. One unittest will be run for each set of input and output files.
+ a separate `Unitttest` for each set of test files using the naming scheme:
+ `test_filename`. One `Unittest` will be run for each set of input and output files.
"""
pass
-"""
-Python Markdown
+# Python Markdown
+
+# A Python implementation of John Gruber's Markdown.
-A Python implementation of John Gruber's Markdown.
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# License: BSD (see LICENSE.md for details).
+
+"""
+Tree processors manipulate the tree created by block processors. They can even create an entirely
+new `ElementTree` object. This is an excellent place for creating summaries, adding collected
+references, or last minute adjustments.
-License: BSD (see LICENSE.md for details).
"""
+from __future__ import annotations
+
+import re
import xml.etree.ElementTree as etree
+from typing import TYPE_CHECKING, Any
from . import util
from . import inlinepatterns
+if TYPE_CHECKING: # pragma: no cover
+ from markdown import Markdown
+
-def build_treeprocessors(md, **kwargs):
- """ Build the default treeprocessors for Markdown. """
+def build_treeprocessors(md: Markdown, **kwargs: Any) -> util.Registry[Treeprocessor]:
+ """ Build the default `treeprocessors` for Markdown. """
treeprocessors = util.Registry()
treeprocessors.register(InlineProcessor(md), 'inline', 20)
treeprocessors.register(PrettifyTreeprocessor(md), 'prettify', 10)
+ treeprocessors.register(UnescapeTreeprocessor(md), 'unescape', 0)
return treeprocessors
-def isString(s):
- """ Check if it's string """
+def isString(s: Any) -> bool:
+ """ Return `True` if object is a string but not an [`AtomicString`][markdown.util.AtomicString]. """
if not isinstance(s, util.AtomicString):
return isinstance(s, str)
return False
class Treeprocessor(util.Processor):
"""
- Treeprocessors are run on the ElementTree object before serialization.
+ `Treeprocessor`s are run on the `ElementTree` object before serialization.
- Each Treeprocessor implements a "run" method that takes a pointer to an
- ElementTree, modifies it as necessary and returns an ElementTree
- object.
+ Each `Treeprocessor` implements a `run` method that takes a pointer to an
+ `Element` and modifies it as necessary.
- Treeprocessors must extend markdown.Treeprocessor.
+ `Treeprocessors` must extend `markdown.Treeprocessor`.
"""
- def run(self, root):
+ def run(self, root: etree.Element) -> etree.Element | None:
"""
- Subclasses of Treeprocessor should implement a `run` method, which
- takes a root ElementTree. This method can return another ElementTree
- object, and the existing root ElementTree will be replaced, or it can
- modify the current tree and return None.
+ Subclasses of `Treeprocessor` should implement a `run` method, which
+ takes a root `Element`. This method can return another `Element`
+ object, and the existing root `Element` will be replaced, or it can
+ modify the current tree and return `None`.
"""
pass # pragma: no cover
class InlineProcessor(Treeprocessor):
"""
- A Treeprocessor that traverses a tree, applying inline patterns.
+ A `Treeprocessor` that traverses a tree, applying inline patterns.
"""
def __init__(self, md):
self.inlinePatterns = md.inlinePatterns
self.ancestors = []
- @property
- @util.deprecated("Use 'md' instead.")
- def markdown(self):
- # TODO: remove this later
- return self.md
-
- def __makePlaceholder(self, type):
+ def __makePlaceholder(self, type) -> tuple[str, str]:
""" Generate a placeholder """
id = "%04d" % len(self.stashed_nodes)
hash = util.INLINE_PLACEHOLDER % id
return hash, id
- def __findPlaceholder(self, data, index):
+ def __findPlaceholder(self, data: str, index: int) -> tuple[str | None, int]:
"""
- Extract id from data string, start from index
-
- Keyword arguments:
+ Extract id from data string, start from index.
- * data: string
- * index: index, from which we start search
+ Arguments:
+ data: String.
+ index: Index, from which we start search.
- Returns: placeholder id and string index, after the found placeholder.
+ Returns:
+ Placeholder id and string index, after the found placeholder.
"""
m = self.__placeholder_re.search(data, index)
else:
return None, index + 1
- def __stashNode(self, node, type):
- """ Add node to stash """
+ def __stashNode(self, node, type) -> str:
+ """ Add node to stash. """
placeholder, id = self.__makePlaceholder(type)
self.stashed_nodes[id] = node
return placeholder
- def __handleInline(self, data, patternIndex=0):
+ def __handleInline(self, data: str, patternIndex: int = 0) -> str:
"""
- Process string with inline patterns and replace it
- with placeholders
-
- Keyword arguments:
+ Process string with inline patterns and replace it with placeholders.
- * data: A line of Markdown text
- * patternIndex: The index of the inlinePattern to start with
+ Arguments:
+ data: A line of Markdown text.
+ patternIndex: The index of the `inlinePattern` to start with.
- Returns: String with placeholders.
+ Returns:
+ String with placeholders.
"""
if not isinstance(data, util.AtomicString):
patternIndex += 1
return data
- def __processElementText(self, node, subnode, isText=True):
+ def __processElementText(self, node: etree.Element, subnode: etree.Element, isText: bool = True):
"""
- Process placeholders in Element.text or Element.tail
- of Elements popped from self.stashed_nodes.
-
- Keywords arguments:
-
- * node: parent node
- * subnode: processing node
- * isText: bool variable, True - it's text, False - it's tail
+ Process placeholders in `Element.text` or `Element.tail`
+ of Elements popped from `self.stashed_nodes`.
- Returns: None
+ Arguments:
+ node: Parent node.
+ subnode: Processing node.
+ isText: Boolean variable, True - it's text, False - it's a tail.
"""
if isText:
for newChild in childResult:
node.insert(pos, newChild[0])
- def __processPlaceholders(self, data, parent, isText=True):
+ def __processPlaceholders(
+ self,
+ data: str,
+ parent: etree.Element,
+ isText: bool = True
+ ) -> list[tuple[etree.Element, Any]]:
"""
- Process string with placeholders and generate ElementTree tree.
-
- Keyword arguments:
+ Process string with placeholders and generate `ElementTree` tree.
- * data: string with placeholders instead of ElementTree elements.
- * parent: Element, which contains processing inline data
+ Arguments:
+ data: String with placeholders instead of `ElementTree` elements.
+ parent: Element, which contains processing inline data.
+ isText: Boolean variable, True - it's text, False - it's a tail.
- Returns: list with ElementTree elements with applied inline patterns.
+ Returns:
+ List with `ElementTree` elements with applied inline patterns.
"""
def linkText(text):
else:
text = data[strartIndex:]
if isinstance(data, util.AtomicString):
- # We don't want to loose the AtomicString
+ # We don't want to loose the `AtomicString`
text = util.AtomicString(text)
linkText(text)
data = ""
return result
- def __applyPattern(self, pattern, data, patternIndex, startIndex=0):
+ def __applyPattern(
+ self,
+ pattern: inlinepatterns.Pattern,
+ data: str,
+ patternIndex: int,
+ startIndex: int = 0
+ ) -> tuple[str, bool, int]:
"""
Check if the line fits the pattern, create the necessary
- elements, add it to stashed_nodes.
-
- Keyword arguments:
+ elements, add it to `stashed_nodes`.
- * data: the text to be processed
- * pattern: the pattern to be checked
- * patternIndex: index of current pattern
- * startIndex: string index, from which we start searching
+ Arguments:
+ data: The text to be processed.
+ pattern: The pattern to be checked.
+ patternIndex: Index of current pattern.
+ startIndex: String index, from which we start searching.
- Returns: String with placeholders instead of ElementTree elements.
+ Returns:
+ String with placeholders instead of `ElementTree` elements.
"""
new_style = isinstance(pattern, inlinepatterns.InlineProcessor)
if new_style:
match = None
- # Since handleMatch may reject our first match,
+ # Since `handleMatch` may reject our first match,
# we iterate over the buffer looking for matches
# until we can't find any more.
for match in pattern.getCompiledRegExp().finditer(data, startIndex):
ancestors.reverse()
parents.extend(ancestors)
- def run(self, tree, ancestors=None):
+ def run(self, tree: etree.Element, ancestors: list[str] | None = None) -> etree.Element:
"""Apply inline patterns to a parsed Markdown tree.
- Iterate over ElementTree, find elements with inline tag, apply inline
- patterns and append newly created Elements to tree. If you don't
- want to process your data with inline patterns, instead of normal
- string, use subclass AtomicString:
+ Iterate over `Element`, find elements with inline tag, apply inline
+ patterns and append newly created Elements to tree. To avoid further
+ processing of string with inline patterns, instead of normal string,
+ use subclass [`AtomicString`][markdown.util.AtomicString]:
- node.text = markdown.AtomicString("This will not be processed.")
+ node.text = markdown.util.AtomicString("This will not be processed.")
Arguments:
+ tree: `Element` object, representing Markdown tree.
+ ancestors: List of parent tag names that precede the tree node (if needed).
- * tree: ElementTree object, representing Markdown tree.
- * ancestors: List of parent tag names that precede the tree node (if needed).
-
- Returns: ElementTree object with applied inline patterns.
+ Returns:
+ An element tree object with applied inline patterns.
"""
- self.stashed_nodes = {}
+ self.stashed_nodes: dict[str, etree.Element] = {}
# Ensure a valid parent list, but copy passed in lists
# to ensure we don't have the user accidentally change it on us.
class PrettifyTreeprocessor(Treeprocessor):
- """ Add linebreaks to the html document. """
+ """ Add line breaks to the html document. """
def _prettifyETree(self, elem):
- """ Recursively add linebreaks to ElementTree children. """
+ """ Recursively add line breaks to `ElementTree` children. """
i = "\n"
if self.md.is_block_level(elem.tag) and elem.tag not in ['code', 'pre']:
for e in elem:
if self.md.is_block_level(e.tag):
self._prettifyETree(e)
- if not elem.tail or not elem.tail.strip():
- elem.tail = i
if not elem.tail or not elem.tail.strip():
elem.tail = i
- def run(self, root):
- """ Add linebreaks to ElementTree root object. """
+ def run(self, root: etree.Element) -> None:
+ """ Add line breaks to `Element` object and its children. """
self._prettifyETree(root)
- # Do <br />'s separately as they are often in the middle of
- # inline content and missed by _prettifyETree.
+ # Do `<br />`'s separately as they are often in the middle of
+ # inline content and missed by `_prettifyETree`.
brs = root.iter('br')
for br in brs:
if not br.tail or not br.tail.strip():
pres = root.iter('pre')
for pre in pres:
if len(pre) and pre[0].tag == 'code':
- pre[0].text = util.AtomicString(pre[0].text.rstrip() + '\n')
+ code = pre[0]
+ # Only prettify code containing text only
+ if not len(code) and code.text is not None:
+ code.text = util.AtomicString(code.text.rstrip() + '\n')
+
+
+class UnescapeTreeprocessor(Treeprocessor):
+ """ Restore escaped chars """
+
+ RE = re.compile(r'{}(\d+){}'.format(util.STX, util.ETX))
+
+ def _unescape(self, m):
+ return chr(int(m.group(1)))
+
+ def unescape(self, text: str) -> str:
+ return self.RE.sub(self._unescape, text)
+
+ def run(self, root):
+ """ Loop over all elements and unescape all text. """
+ for elem in root.iter():
+ # Unescape text content
+ if elem.text and not elem.tag == 'code':
+ elem.text = self.unescape(elem.text)
+ # Unescape tail content
+ if elem.tail:
+ elem.tail = self.unescape(elem.tail)
+ # Unescape attribute values
+ for key, value in elem.items():
+ elem.set(key, self.unescape(value))
-"""
-Python Markdown
+# Python Markdown
+
+# A Python implementation of John Gruber's Markdown.
-A Python implementation of John Gruber's Markdown.
+# Documentation: https://python-markdown.github.io/
+# GitHub: https://github.com/Python-Markdown/markdown/
+# PyPI: https://pypi.org/project/Markdown/
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
+# Started by Manfred Stienstra (http://www.dwerg.net/).
+# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+# Currently maintained by Waylan Limberg (https://github.com/waylan),
+# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
+# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+# Copyright 2004 Manfred Stienstra (the original version)
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
+# License: BSD (see LICENSE.md for details).
-License: BSD (see LICENSE.md for details).
+"""
+This module contains various contacts, classes and functions which get referenced and used
+throughout the code base.
"""
+from __future__ import annotations
+
import re
import sys
import warnings
-import xml.etree.ElementTree
-from collections import namedtuple
-from functools import wraps
+from functools import wraps, lru_cache
from itertools import count
+from typing import TYPE_CHECKING, Generic, Iterator, NamedTuple, TypeVar, overload
-from .pep562 import Pep562
-
-if sys.version_info >= (3, 10):
- from importlib import metadata
-else:
- # <PY310 use backport
- import importlib_metadata as metadata
+if TYPE_CHECKING: # pragma: no cover
+ from markdown import Markdown
-PY37 = (3, 7) <= sys.version_info
-
-
-# TODO: Remove deprecated variables in a future release.
-__deprecated__ = {
- 'etree': ('xml.etree.ElementTree', xml.etree.ElementTree),
- 'string_type': ('str', str),
- 'text_type': ('str', str),
- 'int2str': ('chr', chr),
- 'iterrange': ('range', range)
-}
+_T = TypeVar('_T')
"""
"""
-BLOCK_LEVEL_ELEMENTS = [
+BLOCK_LEVEL_ELEMENTS: list[str] = [
# Elements which are invalid to wrap in a `<p>` tag.
# See https://w3c.github.io/html/grouping-content.html#the-p-element
'address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl',
'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'main', 'menu', 'nav', 'ol',
'p', 'pre', 'section', 'table', 'ul',
# Other elements which Markdown should not be mucking up the contents of.
- 'canvas', 'colgroup', 'dd', 'body', 'dt', 'group', 'iframe', 'li', 'legend',
+ 'canvas', 'colgroup', 'dd', 'body', 'dt', 'group', 'html', 'iframe', 'li', 'legend',
'math', 'map', 'noscript', 'output', 'object', 'option', 'progress', 'script',
- 'style', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'tr', 'video'
+ 'style', 'summary', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'tr', 'video'
]
+"""
+List of HTML tags which get treated as block-level elements. Same as the `block_level_elements`
+attribute of the [`Markdown`][markdown.Markdown] class. Generally one should use the
+attribute on the class. This remains for compatibility with older extensions.
+"""
# Placeholders
-STX = '\u0002' # Use STX ("Start of text") for start-of-placeholder
-ETX = '\u0003' # Use ETX ("End of text") for end-of-placeholder
+STX = '\u0002'
+""" "Start of Text" marker for placeholder templates. """
+ETX = '\u0003'
+""" "End of Text" marker for placeholder templates. """
INLINE_PLACEHOLDER_PREFIX = STX+"klzzwxh:"
+""" Prefix for inline placeholder template. """
INLINE_PLACEHOLDER = INLINE_PLACEHOLDER_PREFIX + "%s" + ETX
+""" Placeholder template for stashed inline text. """
INLINE_PLACEHOLDER_RE = re.compile(INLINE_PLACEHOLDER % r'([0-9]+)')
+""" Regular Expression which matches inline placeholders. """
AMP_SUBSTITUTE = STX+"amp"+ETX
+""" Placeholder template for HTML entities. """
HTML_PLACEHOLDER = STX + "wzxhzdk:%s" + ETX
+""" Placeholder template for raw HTML. """
HTML_PLACEHOLDER_RE = re.compile(HTML_PLACEHOLDER % r'([0-9]+)')
+""" Regular expression which matches HTML placeholders. """
TAG_PLACEHOLDER = STX + "hzzhzkh:%s" + ETX
+""" Placeholder template for tags. """
-"""
-Constants you probably do not need to change
------------------------------------------------------------------------------
-"""
+# Constants you probably do not need to change
+# -----------------------------------------------------------------------------
-# Only load extension entry_points once.
-INSTALLED_EXTENSIONS = metadata.entry_points(group='markdown.extensions')
RTL_BIDI_RANGES = (
('\u0590', '\u07FF'),
# Hebrew (0590-05FF), Arabic (0600-06FF),
)
-"""
-AUXILIARY GLOBAL FUNCTIONS
-=============================================================================
-"""
+# AUXILIARY GLOBAL FUNCTIONS
+# =============================================================================
+
+@lru_cache(maxsize=None)
+def get_installed_extensions():
+ """ Return all entry_points in the `markdown.extensions` group. """
+ if sys.version_info >= (3, 10):
+ from importlib import metadata
+ else: # `<PY310` use backport
+ import importlib_metadata as metadata
+ # Only load extension entry_points once.
+ return metadata.entry_points(group='markdown.extensions')
-def deprecated(message, stacklevel=2):
+
+def deprecated(message: str, stacklevel: int = 2):
"""
- Raise a DeprecationWarning when wrapped function/method is called.
+ Raise a [`DeprecationWarning`][] when wrapped function/method is called.
Usage:
- @deprecated("This method will be removed in version X; use Y instead.")
- def some_method()"
- pass
+
+ ```python
+ @deprecated("This method will be removed in version X; use Y instead.")
+ def some_method():
+ pass
+ ```
"""
def wrapper(func):
@wraps(func)
return wrapper
-@deprecated("Use 'Markdown.is_block_level' instead.")
-def isBlockLevel(tag):
- """Check if the tag is a block level HTML tag."""
- if isinstance(tag, str):
- return tag.lower().rstrip('/') in BLOCK_LEVEL_ELEMENTS
- # Some ElementTree tags are not strings, so return False.
- return False
-
-
-def parseBoolValue(value, fail_on_errors=True, preserve_none=False):
- """Parses a string representing bool value. If parsing was successful,
- returns True or False. If preserve_none=True, returns True, False,
- or None. If parsing was not successful, raises ValueError, or, if
- fail_on_errors=False, returns None."""
+def parseBoolValue(value: str | None, fail_on_errors: bool = True, preserve_none: bool = False) -> bool | None:
+ """Parses a string representing a boolean value. If parsing was successful,
+ returns `True` or `False`. If `preserve_none=True`, returns `True`, `False`,
+ or `None`. If parsing was not successful, raises `ValueError`, or, if
+ `fail_on_errors=False`, returns `None`."""
if not isinstance(value, str):
if preserve_none and value is None:
return value
raise ValueError('Cannot parse bool value: %r' % value)
-def code_escape(text):
- """Escape code."""
+def code_escape(text: str) -> str:
+ """HTML escape a string of code."""
if "&" in text:
text = text.replace("&", "&")
if "<" in text:
return size
-def nearing_recursion_limit():
+def nearing_recursion_limit() -> bool:
"""Return true if current stack depth is within 100 of maximum limit."""
return sys.getrecursionlimit() - _get_stack_depth() < 100
-"""
-MISC AUXILIARY CLASSES
-=============================================================================
-"""
+# MISC AUXILIARY CLASSES
+# =============================================================================
class AtomicString(str):
class Processor:
- def __init__(self, md=None):
- self.md = md
+ """ The base class for all processors.
+
+ Attributes:
+ Processor.md: The `Markdown` instance passed in an initialization.
+
+ Arguments:
+ md: The `Markdown` instance this processor is a part of.
- @property
- @deprecated("Use 'md' instead.")
- def markdown(self):
- # TODO: remove this later
- return self.md
+ """
+ def __init__(self, md: Markdown | None = None):
+ self.md = md
class HtmlStash:
"""
def __init__(self):
- """ Create a HtmlStash. """
+ """ Create an `HtmlStash`. """
self.html_counter = 0 # for counting inline html segments
self.rawHtmlBlocks = []
self.tag_counter = 0
self.tag_data = [] # list of dictionaries in the order tags appear
- def store(self, html):
+ def store(self, html: str) -> str:
"""
Saves an HTML segment for later reinsertion. Returns a
placeholder string that needs to be inserted into the
document.
Keyword arguments:
+ html: An html segment.
- * html: an html segment
-
- Returns : a placeholder string
+ Returns:
+ A placeholder string.
"""
self.rawHtmlBlocks.append(html)
self.html_counter += 1
return placeholder
- def reset(self):
+ def reset(self) -> None:
+ """ Clear the stash. """
self.html_counter = 0
self.rawHtmlBlocks = []
- def get_placeholder(self, key):
+ def get_placeholder(self, key: int) -> str:
return HTML_PLACEHOLDER % key
- def store_tag(self, tag, attrs, left_index, right_index):
+ def store_tag(self, tag: str, attrs: list, left_index: int, right_index: int) -> str:
"""Store tag data and return a placeholder."""
self.tag_data.append({'tag': tag, 'attrs': attrs,
'left_index': left_index,
'right_index': right_index})
placeholder = TAG_PLACEHOLDER % str(self.tag_counter)
- self.tag_counter += 1 # equal to the tag's index in self.tag_data
+ self.tag_counter += 1 # equal to the tag's index in `self.tag_data`
return placeholder
# Used internally by `Registry` for each item in its sorted list.
# Provides an easier to read API when editing the code later.
# For example, `item.name` is more clear than `item[0]`.
-_PriorityItem = namedtuple('PriorityItem', ['name', 'priority'])
+class _PriorityItem(NamedTuple):
+ name: str
+ priority: float
-class Registry:
+class Registry(Generic[_T]):
"""
A priority sorted registry.
"""
def __init__(self):
- self._data = {}
+ self._data: dict[str, _T] = {}
self._priority = []
self._is_sorted = False
- def __contains__(self, item):
+ def __contains__(self, item: str | _T) -> bool:
if isinstance(item, str):
# Check if an item exists by this name.
return item in self._data.keys()
# Check if this instance exists.
return item in self._data.values()
- def __iter__(self):
+ def __iter__(self) -> Iterator[_T]:
self._sort()
return iter([self._data[k] for k, p in self._priority])
- def __getitem__(self, key):
+ @overload
+ def __getitem__(self, key: str | int) -> _T: # pragma: no cover
+ ...
+
+ @overload
+ def __getitem__(self, key: slice) -> Registry[_T]: # pragma: no cover
+ ...
+
+ def __getitem__(self, key: str | int | slice) -> _T | Registry[_T]:
self._sort()
if isinstance(key, slice):
- data = Registry()
+ data: Registry[_T] = Registry()
for k, p in self._priority[key]:
data.register(self._data[k], k, p)
return data
return self._data[self._priority[key].name]
return self._data[key]
- def __len__(self):
+ def __len__(self) -> int:
return len(self._priority)
def __repr__(self):
return '<{}({})>'.format(self.__class__.__name__, list(self))
- def get_index_for_name(self, name):
+ def get_index_for_name(self, name: str) -> int:
"""
Return the index of the given name.
"""
)
raise ValueError('No item named "{}" exists.'.format(name))
- def register(self, item, name, priority):
+ def register(self, item: _T, name: str, priority: float) -> None:
"""
Add an item to the registry with the given name and priority.
- Parameters:
-
- * `item`: The item being registered.
- * `name`: A string used to reference the item.
- * `priority`: An integer or float used to sort against all items.
+ Arguments:
+ item: The item being registered.
+ name: A string used to reference the item.
+ priority: An integer or float used to sort against all items.
If an item is registered with a "name" which already exists, the
existing item is replaced with the new item. Treat carefully as the
self._data[name] = item
self._priority.append(_PriorityItem(name, priority))
- def deregister(self, name, strict=True):
+ def deregister(self, name: str, strict: bool = True) -> None:
"""
Remove an item from the registry.
- Set `strict=False` to fail silently.
+ Set `strict=False` to fail silently. Otherwise a [`ValueError`][] is raised for an unknown `name`.
"""
try:
index = self.get_index_for_name(name)
if not self._is_sorted:
self._priority.sort(key=lambda item: item.priority, reverse=True)
self._is_sorted = True
-
- # Deprecated Methods which provide a smooth transition from OrderedDict
-
- def __setitem__(self, key, value):
- """ Register item with priority 5 less than lowest existing priority. """
- if isinstance(key, str):
- warnings.warn(
- 'Using setitem to register a processor or pattern is deprecated. '
- 'Use the `register` method instead.',
- DeprecationWarning,
- stacklevel=2,
- )
- if key in self:
- # Key already exists, replace without altering priority
- self._data[key] = value
- return
- if len(self) == 0:
- # This is the first item. Set priority to 50.
- priority = 50
- else:
- self._sort()
- priority = self._priority[-1].priority - 5
- self.register(value, key, priority)
- else:
- raise TypeError
-
- def __delitem__(self, key):
- """ Deregister an item by name. """
- if key in self:
- self.deregister(key)
- warnings.warn(
- 'Using del to remove a processor or pattern is deprecated. '
- 'Use the `deregister` method instead.',
- DeprecationWarning,
- stacklevel=2,
- )
- else:
- raise KeyError('Cannot delete key {}, not registered.'.format(key))
-
- def add(self, key, value, location):
- """ Register a key by location. """
- if len(self) == 0:
- # This is the first item. Set priority to 50.
- priority = 50
- elif location == '_begin':
- self._sort()
- # Set priority 5 greater than highest existing priority
- priority = self._priority[0].priority + 5
- elif location == '_end':
- self._sort()
- # Set priority 5 less than lowest existing priority
- priority = self._priority[-1].priority - 5
- elif location.startswith('<') or location.startswith('>'):
- # Set priority halfway between existing priorities.
- i = self.get_index_for_name(location[1:])
- if location.startswith('<'):
- after = self._priority[i].priority
- if i > 0:
- before = self._priority[i-1].priority
- else:
- # Location is first item`
- before = after + 10
- else:
- # location.startswith('>')
- before = self._priority[i].priority
- if i < len(self) - 1:
- after = self._priority[i+1].priority
- else:
- # location is last item
- after = before - 10
- priority = before - ((before - after) / 2)
- else:
- raise ValueError('Not a valid location: "%s". Location key '
- 'must start with a ">" or "<".' % location)
- self.register(value, key, priority)
- warnings.warn(
- 'Using the add method to register a processor or pattern is deprecated. '
- 'Use the `register` method instead.',
- DeprecationWarning,
- stacklevel=2,
- )
-
-
-def __getattr__(name):
- """Get attribute."""
-
- deprecated = __deprecated__.get(name)
- if deprecated:
- warnings.warn(
- "'{}' is deprecated. Use '{}' instead.".format(name, deprecated[0]),
- category=DeprecationWarning,
- stacklevel=(3 if PY37 else 4)
- )
- return deprecated[1]
- raise AttributeError("module '{}' has no attribute '{}'".format(__name__, name))
-
-
-if not PY37:
- Pep562(__name__)
site_url: https://Python-Markdown.github.io/
repo_url: https://github.com/Python-Markdown/markdown
site_author: "The Python-Markdown Project"
-copyright: "Copyright © 2010-2017"
+copyright: "Copyright © 2010-2023"
use_directory_urls: true
+watch: [markdown, scripts]
theme:
name: nature
release: !!python/name:markdown.__version__
issue_tracker: https://github.com/Python-Markdown/markdown/issues
+extra_css:
+ - custom.css
+ - mkdocstrings.css
+
nav:
- Python-Markdown: index.md
- Installation: install.md
- WikiLinks: extensions/wikilinks.md
- Extension API: extensions/api.md
- Test Tools: test_tools.md
+ - API Reference: reference/
- Contributing to Python-Markdown: contributing.md
- - Change Log: change_log/index.md
- - Release Notes for v.3.3: change_log/release-3.3.md
- - Release Notes for v.3.2: change_log/release-3.2.md
- - Release Notes for v.3.1: change_log/release-3.1.md
- - Release Notes for v.3.0: change_log/release-3.0.md
- - Release Notes for v.2.6: change_log/release-2.6.md
- - Release Notes for v.2.5: change_log/release-2.5.md
- - Release Notes for v.2.4: change_log/release-2.4.md
- - Release Notes for v.2.3: change_log/release-2.3.md
- - Release Notes for v.2.2: change_log/release-2.2.md
- - Release Notes for v.2.1: change_log/release-2.1.md
- - Release Notes for v.2.0: change_log/release-2.0.md
+ - Changelog: changelog.md
- Authors: authors.md
+not_in_nav: |
+ change_log/
+
markdown_extensions:
- extra
- admonition
- codehilite
- toc:
permalink: true
+ - mdx_gh_links:
+ user: Python-Markdown
+ repo: markdown
+
+plugins:
+- gen-files:
+ scripts:
+ - scripts/gen_ref_nav.py
+- literate-nav:
+ nav_file: SUMMARY.md
+- section-index
+- mkdocstrings:
+ custom_templates: docs/templates
+ handlers:
+ python:
+ import:
+ - https://docs.python.org/3/objects.inv
+ options:
+ annotations_path: brief
+ docstring_options:
+ ignore_init_summary: true
+ docstring_style: google
+ docstring_section_style: list
+ extensions:
+ - scripts/griffe_extensions.py:DeprecatedExtension
+ - scripts/griffe_extensions.py:PriorityTableExtension:
+ paths:
+ - markdown.preprocessors.build_preprocessors
+ - markdown.blockprocessors.build_block_parser
+ - markdown.treeprocessors.build_treeprocessors
+ - markdown.inlinepatterns.build_inlinepatterns
+ - markdown.postprocessors.build_postprocessors
+ filters: ["!^_"]
+ group_by_category: false
+ heading_level: 1
+ inherited_members: true
+ members_order: source
+ merge_init_into_class: true
+ separate_signature: false
+ show_root_heading: true
+ show_object_full_path: true
+ show_signature_annotations: true
+ show_source: false
+ show_symbol_type_heading: true
+ show_symbol_type_toc: true
+ signature_crossrefs: false
+ summary: true
+ source:
+ repo: https://github.com/Python-Markdown/markdown
+ tag: !!python/name:markdown.__version__
+ title: "View source code on GitHub."
[build-system]
# Minimum requirements for the build system to execute.
-requires = ["setuptools>=36.6", "wheel"]
+requires = ["setuptools>=61.2"]
build-backend = "setuptools.build_meta"
+
+[project]
+name = 'Markdown'
+dynamic = ['version']
+description = "Python implementation of John Gruber's Markdown."
+readme = {file = 'README.md', content-type='text/markdown'}
+authors = [
+ {name = 'Manfred Stienstra'},
+ {name = 'Yuri Takhteyev'},
+ {name = 'Waylan limberg', email = 'python.markdown@gmail.com'}
+]
+maintainers = [
+ {name = 'Waylan Limberg', email = 'python.markdown@gmail.com'},
+ {name = 'Isaac Muse'}
+]
+license = {file = 'LICENSE.md'}
+requires-python = '>=3.8'
+dependencies = [
+ "importlib-metadata>=4.4;python_version<'3.10'"
+]
+keywords = ['markdown', 'markdown-parser', 'python-markdown', 'markdown-to-html']
+classifiers = [
+ 'Development Status :: 5 - Production/Stable',
+ 'License :: OSI Approved :: BSD License',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.8',
+ 'Programming Language :: Python :: 3.9',
+ 'Programming Language :: Python :: 3.10',
+ 'Programming Language :: Python :: 3.11',
+ 'Programming Language :: Python :: 3.12',
+ 'Programming Language :: Python :: 3 :: Only',
+ 'Programming Language :: Python :: Implementation :: CPython',
+ 'Programming Language :: Python :: Implementation :: PyPy',
+ 'Topic :: Communications :: Email :: Filters',
+ 'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries',
+ 'Topic :: Internet :: WWW/HTTP :: Site Management',
+ 'Topic :: Software Development :: Documentation',
+ 'Topic :: Software Development :: Libraries :: Python Modules',
+ 'Topic :: Text Processing :: Filters',
+ 'Topic :: Text Processing :: Markup :: HTML',
+ 'Topic :: Text Processing :: Markup :: Markdown'
+]
+
+[project.optional-dependencies]
+testing = [
+ 'coverage',
+ 'pyyaml'
+]
+docs = [
+ 'mkdocs>=1.5',
+ 'mkdocs-nature>=0.6',
+ 'mdx_gh_links>=0.2',
+ "mkdocstrings[python]",
+ "mkdocs-gen-files",
+ "mkdocs-section-index",
+ "mkdocs-literate-nav",
+]
+
+[project.urls]
+'Homepage' = 'https://Python-Markdown.github.io/'
+'Documentation' = 'https://Python-Markdown.github.io/'
+'Repository' = 'https://github.com/Python-Markdown/markdown'
+'Issue Tracker' = 'https://github.com/Python-Markdown/markdown/issues'
+'Changelog' = 'https://github.com/Python-Markdown/markdown/blob/master/docs/change_log/index.md'
+
+[project.scripts]
+markdown_py = 'markdown.__main__:run'
+
+[project.entry-points.'markdown.extensions']
+abbr = 'markdown.extensions.abbr:AbbrExtension'
+admonition = 'markdown.extensions.admonition:AdmonitionExtension'
+attr_list = 'markdown.extensions.attr_list:AttrListExtension'
+codehilite = 'markdown.extensions.codehilite:CodeHiliteExtension'
+def_list = 'markdown.extensions.def_list:DefListExtension'
+extra = 'markdown.extensions.extra:ExtraExtension'
+fenced_code = 'markdown.extensions.fenced_code:FencedCodeExtension'
+footnotes = 'markdown.extensions.footnotes:FootnoteExtension'
+md_in_html = 'markdown.extensions.md_in_html:MarkdownInHtmlExtension'
+meta = 'markdown.extensions.meta:MetaExtension'
+nl2br = 'markdown.extensions.nl2br:Nl2BrExtension'
+sane_lists = 'markdown.extensions.sane_lists:SaneListExtension'
+smarty = 'markdown.extensions.smarty:SmartyExtension'
+tables = 'markdown.extensions.tables:TableExtension'
+toc = 'markdown.extensions.toc:TocExtension'
+wikilinks = 'markdown.extensions.wikilinks:WikiLinkExtension'
+legacy_attrs = 'markdown.extensions.legacy_attrs:LegacyAttrExtension'
+legacy_em = 'markdown.extensions.legacy_em:LegacyEmExtension'
+
+[tool.setuptools]
+packages = ['markdown', 'markdown.extensions']
+
+[tool.setuptools.dynamic]
+version = {attr = 'markdown.__meta__.__version__'}
-[metadata]
-license_file = LICENSE.md
+[egg_info]
+tag_build =
+tag_date = 0
+
+++ /dev/null
-#!/usr/bin/env python
-"""
-Python Markdown
-
-A Python implementation of John Gruber's Markdown.
-
-Documentation: https://python-markdown.github.io/
-GitHub: https://github.com/Python-Markdown/markdown/
-PyPI: https://pypi.org/project/Markdown/
-
-Started by Manfred Stienstra (http://www.dwerg.net/).
-Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
-Currently maintained by Waylan Limberg (https://github.com/waylan),
-Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
-Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
-Copyright 2004 Manfred Stienstra (the original version)
-
-License: BSD (see LICENSE.md for details).
-"""
-
-
-import os
-from setuptools import setup
-
-
-def get_version():
- """Get version and version_info from markdown/__meta__.py file."""
- module_path = os.path.join(os.path.dirname('__file__'), 'markdown', '__meta__.py')
-
- import importlib.util
- spec = importlib.util.spec_from_file_location('__meta__', module_path)
- meta = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(meta)
- return meta.__version__, meta.__version_info__
-
-
-__version__, __version_info__ = get_version()
-
-# Get development Status for classifiers
-dev_status_map = {
- 'dev': '2 - Pre-Alpha',
- 'alpha': '3 - Alpha',
- 'beta': '4 - Beta',
- 'rc': '4 - Beta',
- 'final': '5 - Production/Stable'
-}
-DEVSTATUS = dev_status_map[__version_info__[3]]
-
-# The command line script name. Currently set to "markdown_py" so as not to
-# conflict with the perl implementation (which uses "markdown").
-SCRIPT_NAME = 'markdown_py'
-
-with open('README.md') as f:
- long_description = f.read()
-
-setup(
- name='Markdown',
- version=__version__,
- url='https://Python-Markdown.github.io/',
- project_urls={
- 'Documentation': 'https://Python-Markdown.github.io/',
- 'GitHub Project': 'https://github.com/Python-Markdown/markdown',
- 'Issue Tracker': 'https://github.com/Python-Markdown/markdown/issues'
- },
- description='Python implementation of Markdown.',
- long_description=long_description,
- long_description_content_type='text/markdown',
- author='Manfred Stienstra, Yuri takhteyev and Waylan limberg',
- author_email='python.markdown@gmail.com',
- maintainer='Waylan Limberg',
- maintainer_email='python.markdown@gmail.com',
- license='BSD License',
- packages=['markdown', 'markdown.extensions'],
- python_requires='>=3.6',
- install_requires=["importlib-metadata>=4.4;python_version<'3.10'"],
- extras_require={
- 'testing': [
- 'coverage',
- 'pyyaml',
- ],
- },
- entry_points={
- 'console_scripts': [
- '%s = markdown.__main__:run' % SCRIPT_NAME,
- ],
- # Register the built in extensions
- 'markdown.extensions': [
- 'abbr = markdown.extensions.abbr:AbbrExtension',
- 'admonition = markdown.extensions.admonition:AdmonitionExtension',
- 'attr_list = markdown.extensions.attr_list:AttrListExtension',
- 'codehilite = markdown.extensions.codehilite:CodeHiliteExtension',
- 'def_list = markdown.extensions.def_list:DefListExtension',
- 'extra = markdown.extensions.extra:ExtraExtension',
- 'fenced_code = markdown.extensions.fenced_code:FencedCodeExtension',
- 'footnotes = markdown.extensions.footnotes:FootnoteExtension',
- 'md_in_html = markdown.extensions.md_in_html:MarkdownInHtmlExtension',
- 'meta = markdown.extensions.meta:MetaExtension',
- 'nl2br = markdown.extensions.nl2br:Nl2BrExtension',
- 'sane_lists = markdown.extensions.sane_lists:SaneListExtension',
- 'smarty = markdown.extensions.smarty:SmartyExtension',
- 'tables = markdown.extensions.tables:TableExtension',
- 'toc = markdown.extensions.toc:TocExtension',
- 'wikilinks = markdown.extensions.wikilinks:WikiLinkExtension',
- 'legacy_attrs = markdown.extensions.legacy_attrs:LegacyAttrExtension',
- 'legacy_em = markdown.extensions.legacy_em:LegacyEmExtension',
- ]
- },
- classifiers=[
- 'Development Status :: %s' % DEVSTATUS,
- 'License :: OSI Approved :: BSD License',
- 'Operating System :: OS Independent',
- 'Programming Language :: Python',
- 'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.6',
- 'Programming Language :: Python :: 3.7',
- 'Programming Language :: Python :: 3.8',
- 'Programming Language :: Python :: 3.9',
- 'Programming Language :: Python :: 3.10',
- 'Programming Language :: Python :: 3 :: Only',
- 'Programming Language :: Python :: Implementation :: CPython',
- 'Programming Language :: Python :: Implementation :: PyPy',
- 'Topic :: Communications :: Email :: Filters',
- 'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries',
- 'Topic :: Internet :: WWW/HTTP :: Site Management',
- 'Topic :: Software Development :: Documentation',
- 'Topic :: Software Development :: Libraries :: Python Modules',
- 'Topic :: Text Processing :: Filters',
- 'Topic :: Text Processing :: Markup :: HTML',
- 'Topic :: Text Processing :: Markup :: Markdown'
- ]
-)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
<p>Right bracket: ]</p>
<p>Left paren: (</p>
<p>Right paren: )</p>
-<p>Greater-than: ></p>
+<p>Greater-than: ></p>
<p>Hash: #</p>
<p>Period: .</p>
<p>Bang: !</p>
<pre><code>I strongly recommend against using any `<blink>` tags.
I wish SmartyPants used named entities like `&mdash;`
-instead of decimal-encoded entites like `&#8212;`.
+instead of decimal-encoded entities like `&#8212;`.
</code></pre>
<p>Output:</p>
<pre><code><p>I strongly recommend against using any
<p>I wish SmartyPants used named entities like
<code>&amp;mdash;</code> instead of decimal-encoded
-entites like <code>&amp;#8212;</code>.</p>
+entities like <code>&amp;#8212;</code>.</p>
</code></pre>
<p>To specify an entire block of pre-formatted code, indent every line of
the block by 4 spaces or 1 tab. Just like with code spans, <code>&</code>, <code><</code>,
I strongly recommend against using any `<blink>` tags.
I wish SmartyPants used named entities like `—`
- instead of decimal-encoded entites like `—`.
+ instead of decimal-encoded entities like `—`.
Output:
<p>I wish SmartyPants used named entities like
<code>&mdash;</code> instead of decimal-encoded
- entites like <code>&#8212;</code>.</p>
+ entities like <code>&#8212;</code>.</p>
To specify an entire block of pre-formatted code, indent every line of
+++ /dev/null
-<h2>Table Tests</h2>
-<table>
-<thead>
-<tr>
-<th>First Header</th>
-<th>Second Header</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>Content Cell</td>
-<td>Content Cell</td>
-</tr>
-<tr>
-<td>Content Cell</td>
-<td>Content Cell</td>
-</tr>
-</tbody>
-</table>
-<table>
-<thead>
-<tr>
-<th>First Header</th>
-<th>Second Header</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>Content Cell</td>
-<td>Content Cell</td>
-</tr>
-<tr>
-<td>Content Cell</td>
-<td>Content Cell</td>
-</tr>
-</tbody>
-</table>
-<table>
-<thead>
-<tr>
-<th align="left">Item</th>
-<th align="right">Value</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td align="left">Computer</td>
-<td align="right">$1600</td>
-</tr>
-<tr>
-<td align="left">Phone</td>
-<td align="right">$12</td>
-</tr>
-<tr>
-<td align="left">Pipe</td>
-<td align="right">$1</td>
-</tr>
-</tbody>
-</table>
-<table>
-<thead>
-<tr>
-<th>Function name</th>
-<th>Description</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td><code>help()</code></td>
-<td>Display the help window.</td>
-</tr>
-<tr>
-<td><code>destroy()</code></td>
-<td><strong>Destroy your computer!</strong></td>
-</tr>
-</tbody>
-</table>
-<table>
-<thead>
-<tr>
-<th align="left">foo</th>
-<th align="center">bar</th>
-<th align="right">baz</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td align="left"></td>
-<td align="center">Q</td>
-<td align="right"></td>
-</tr>
-<tr>
-<td align="left">W</td>
-<td align="center"></td>
-<td align="right">W</td>
-</tr>
-</tbody>
-</table>
-<table>
-<thead>
-<tr>
-<th>foo</th>
-<th>bar</th>
-<th>baz</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td></td>
-<td>Q</td>
-<td></td>
-</tr>
-<tr>
-<td>W</td>
-<td></td>
-<td>W</td>
-</tr>
-</tbody>
-</table>
-<p>Three spaces in front of a table:</p>
-<table>
-<thead>
-<tr>
-<th>First Header</th>
-<th>Second Header</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>Content Cell</td>
-<td>Content Cell</td>
-</tr>
-<tr>
-<td>Content Cell</td>
-<td>Content Cell</td>
-</tr>
-</tbody>
-</table>
-<table>
-<thead>
-<tr>
-<th>First Header</th>
-<th>Second Header</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>Content Cell</td>
-<td>Content Cell</td>
-</tr>
-<tr>
-<td>Content Cell</td>
-<td>Content Cell</td>
-</tr>
-</tbody>
-</table>
-<p>Four spaces is a code block:</p>
-<pre><code>First Header | Second Header
------------- | -------------
-Content Cell | Content Cell
-Content Cell | Content Cell
-</code></pre>
-<table>
-<thead>
-<tr>
-<th>First Header</th>
-<th>Second Header</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td></td>
-<td></td>
-</tr>
-</tbody>
-</table>
-<p>More inline code block tests</p>
-<table>
-<thead>
-<tr>
-<th>Column 1</th>
-<th>Column 2</th>
-<th>Column 3</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>word 1</td>
-<td>word 2</td>
-<td>word 3</td>
-</tr>
-<tr>
-<td>word 1</td>
-<td><code>word 2</code></td>
-<td>word 3</td>
-</tr>
-<tr>
-<td>word 1</td>
-<td>`word 2</td>
-<td>word 3</td>
-</tr>
-<tr>
-<td>word 1</td>
-<td>`word 2</td>
-<td>word 3</td>
-</tr>
-<tr>
-<td>word 1</td>
-<td><code>word |2</code></td>
-<td>word 3</td>
-</tr>
-<tr>
-<td>words</td>
-<td><code>some | code</code></td>
-<td>more words</td>
-</tr>
-<tr>
-<td>words</td>
-<td><code>some | code</code></td>
-<td>more words</td>
-</tr>
-<tr>
-<td>words</td>
-<td><code>some | code</code></td>
-<td>more words</td>
-</tr>
-<tr>
-<td>words</td>
-<td><code>some ` | ` code</code></td>
-<td>more words</td>
-</tr>
-<tr>
-<td>words</td>
-<td><code>some ` | ` code</code></td>
-<td>more words</td>
-</tr>
-<tr>
-<td>words</td>
-<td><code>some ` | ` code</code></td>
-<td>more words</td>
-</tr>
-</tbody>
-</table>
-<p>A test for issue #440:</p>
-<table>
-<thead>
-<tr>
-<th>foo</th>
-<th>bar</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>foo</td>
-<td>(<code>bar</code>) and <code>baz</code>.</td>
-</tr>
-</tbody>
-</table>
-<p>Lists are not tables</p>
-<ul>
-<li>this | should | not</li>
-<li>be | a | table</li>
-</ul>
-<p>Add tests for issue #449</p>
-<table>
-<thead>
-<tr>
-<th>Odd backticks</th>
-<th>Even backticks</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td><code>[!\"\#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]</code></td>
-<td><code>[!\"\#$%&'()*+,\-./:;<=>?@\[\\\]^`_`{|}~]</code></td>
-</tr>
-</tbody>
-</table>
-<table>
-<thead>
-<tr>
-<th>Escapes</th>
-<th>More Escapes</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td><code>`\</code></td>
-<td><code>\</code></td>
-</tr>
-</tbody>
-</table>
-<p>Only the first backtick can be escaped</p>
-<table>
-<thead>
-<tr>
-<th>Escaped</th>
-<th>Bacticks</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>`<code>\</code></td>
-<td>``</td>
-</tr>
-</tbody>
-</table>
-<p>Test escaped pipes</p>
-<table>
-<thead>
-<tr>
-<th>Column 1</th>
-<th>Column 2</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td><code>|</code> |</td>
-<td>Pipes are okay in code and escaped. |</td>
-</tr>
-</tbody>
-</table>
-<table>
-<thead>
-<tr>
-<th>Column 1</th>
-<th>Column 2</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>row1</td>
-<td>row1 |</td>
-</tr>
-<tr>
-<td>row2</td>
-<td>row2</td>
-</tr>
-</tbody>
-</table>
-<p>Test header escapes</p>
-<table>
-<thead>
-<tr>
-<th><code>`\</code> |</th>
-<th><code>\</code> |</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>row1</td>
-<td>row1</td>
-</tr>
-<tr>
-<td>row2</td>
-<td>row2</td>
-</tr>
-</tbody>
-</table>
-<p>Escaped pipes in format row should not be a table</p>
-<p>| Column1 | Column2 |
-| ------- || ------- |
-| row1 | row1 |
-| row2 | row2 |</p>
-<p>Test escaped code in Table</p>
-<table>
-<thead>
-<tr>
-<th>Should not be code</th>
-<th>Should be code</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>`Not code`</td>
-<td>\<code>code</code></td>
-</tr>
-<tr>
-<td>\`Not code\`</td>
-<td>\\<code>code</code></td>
-</tr>
-</tbody>
-</table>
-<p>Single column tables</p>
-<table>
-<thead>
-<tr>
-<th>Is a Table</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td></td>
-</tr>
-</tbody>
-</table>
-<table>
-<thead>
-<tr>
-<th>Is a Table</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td></td>
-</tr>
-</tbody>
-</table>
-<table>
-<thead>
-<tr>
-<th>Is a Table</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td></td>
-</tr>
-</tbody>
-</table>
-<table>
-<thead>
-<tr>
-<th>Is a Table</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>row</td>
-</tr>
-</tbody>
-</table>
-<table>
-<thead>
-<tr>
-<th>Is a Table</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>row</td>
-</tr>
-</tbody>
-</table>
-<table>
-<thead>
-<tr>
-<th>Is a Table</th>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>row</td>
-</tr>
-</tbody>
-</table>
-<h2>| Is not a Table</h2>
-<p>| row</p>
-<h2>Is not a Table |</h2>
-<p>row |</p>
-<p>| Is not a Table
-| --------------
-row</p>
-<p>Is not a Table |
--------------- |
-row</p>
\ No newline at end of file
+++ /dev/null
-Table Tests
------------
-
-First Header | Second Header
-------------- | -------------
-Content Cell | Content Cell
-Content Cell | Content Cell
-
-| First Header | Second Header |
-| ------------- | ------------- |
-| Content Cell | Content Cell |
-| Content Cell | Content Cell |
-
-| Item | Value |
-| :-------- | -----:|
-| Computer | $1600 |
-| Phone | $12 |
-| Pipe | $1 |
-
-| Function name | Description |
-| ------------- | ------------------------------ |
-| `help()` | Display the help window. |
-| `destroy()` | **Destroy your computer!** |
-
-|foo|bar|baz|
-|:--|:-:|--:|
-| | Q | |
-|W | | W|
-
-foo|bar|baz
----|---|---
- | Q |
- W | | W
-
-Three spaces in front of a table:
-
- First Header | Second Header
- ------------ | -------------
- Content Cell | Content Cell
- Content Cell | Content Cell
-
- | First Header | Second Header |
- | ------------ | ------------- |
- | Content Cell | Content Cell |
- | Content Cell | Content Cell |
-
-Four spaces is a code block:
-
- First Header | Second Header
- ------------ | -------------
- Content Cell | Content Cell
- Content Cell | Content Cell
-
-| First Header | Second Header |
-| ------------ | ------------- |
-
-More inline code block tests
-
-Column 1 | Column 2 | Column 3
----------|----------|---------
-word 1 | word 2 | word 3
-word 1 | `word 2` | word 3
-word 1 | \`word 2 | word 3
-word 1 | `word 2 | word 3
-word 1 | `word |2` | word 3
-words |`` some | code `` | more words
-words |``` some | code ``` | more words
-words |```` some | code ```` | more words
-words |`` some ` | ` code `` | more words
-words |``` some ` | ` code ``` | more words
-words |```` some ` | ` code ```` | more words
-
-A test for issue #440:
-
-foo | bar
---- | ---
-foo | (`bar`) and `baz`.
-
-Lists are not tables
-
- - this | should | not
- - be | a | table
-
-Add tests for issue #449
-
-Odd backticks | Even backticks
------------- | -------------
-``[!\"\#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]`` | ``[!\"\#$%&'()*+,\-./:;<=>?@\[\\\]^`_`{|}~]``
-
-Escapes | More Escapes
-------- | ------
-`` `\`` | `\`
-
-Only the first backtick can be escaped
-
-Escaped | Bacticks
-------- | ------
-\`` \` | \`\`
-
-Test escaped pipes
-
-Column 1 | Column 2
--------- | --------
-`|` \| | Pipes are okay in code and escaped. \|
-
-| Column 1 | Column 2 |
-| -------- | -------- |
-| row1 | row1 \|
-| row2 | row2 |
-
-Test header escapes
-
-| `` `\`` \| | `\` \|
-| ---------- | ---- |
-| row1 | row1 |
-| row2 | row2 |
-
-Escaped pipes in format row should not be a table
-
-| Column1 | Column2 |
-| ------- \|| ------- |
-| row1 | row1 |
-| row2 | row2 |
-
-Test escaped code in Table
-
-Should not be code | Should be code
------------------- | --------------
-\`Not code\` | \\`code`
-\\\`Not code\\\` | \\\\`code`
-
-Single column tables
-
-| Is a Table |
-| ---------- |
-
-| Is a Table
-| ----------
-
-Is a Table |
----------- |
-
-| Is a Table |
-| ---------- |
-| row |
-
-| Is a Table
-| ----------
-| row
-
-Is a Table |
----------- |
-row |
-
-| Is not a Table
---------------
-| row
-
-Is not a Table |
---------------
-row |
-
-| Is not a Table
-| --------------
-row
-
-Is not a Table |
--------------- |
-row
+++ /dev/null
-<p>’.<br />
-1440–80’s<br />
-1440–’80s<br />
-1440—’80s<br />
-1960s<br />
-1960’s<br />
-one two ’60s<br />
-’60s</p>
-<p>It’s fun. What’s fun?<br />
-“Isn’t this fun”? — she said…<br />
-“‘Quoted’ words in a larger quote.”<br />
-‘Quoted “words” in a larger quote.’<br />
-“quoted” text and <strong>bold “quoted” text</strong><br />
-‘quoted’ text and <strong>bold ‘quoted’ text</strong><br />
-em-dashes (—) and ellipes (…)<br />
-“<a href="http://example.com">Link</a>” — she said.</p>
-<p>“Ellipsis within quotes…”</p>
-<p>Кавычки-«Ñ‘лочки»<br />
-«hello»<br />
-Anführungszeichen-»Chevrons«</p>
-<hr />
-<p>Escaped -- ndash<br />
-'Escaped' "quotes"<br />
-Escaped ellipsis...</p>
-<p>‘Escaped "quotes" in real ones’<br />
-'“Real” quotes in escaped ones'</p>
-<p>Skip <code><<all>> "code" -- --- 'spans' ...</code>.</p>
-<pre><code>Also skip "code" 'blocks'
-foo -- bar --- baz ...
-</code></pre>
-<p>A line that ‘wraps’ with
-<em>emphasis</em> at the beginning of the next line.</p>
\ No newline at end of file
+++ /dev/null
-'.
-1440--80's
-1440--'80s
-1440---'80s
-1960s
-1960's
-one two '60s
-'60s
-
-It's fun. What's fun?
-"Isn't this fun"? --- she said...
-"'Quoted' words in a larger quote."
-'Quoted "words" in a larger quote.'
-"quoted" text and **bold "quoted" text**
-'quoted' text and **bold 'quoted' text**
-em-dashes (---) and ellipes (...)
-"[Link](http://example.com)" --- she said.
-
-"Ellipsis within quotes..."
-
-Кавычки-<<ёлочки>>
-<<hello>>
-Anführungszeichen->>Chevrons<<
-
---- -- ---
-
-Escaped \-- ndash
-\'Escaped\' \"quotes\"
-Escaped ellipsis\...
-
-'Escaped \"quotes\" in real ones'
-\'"Real" quotes in escaped ones\'
-
-Skip `<<all>> "code" -- --- 'spans' ...`.
-
- Also skip "code" 'blocks'
- foo -- bar --- baz ...
-
-A line that 'wraps' with
-*emphasis* at the beginning of the next line.
+++ /dev/null
-construction:0.000000:0.000000
-CRLF_line_ends:0.020000:0.000000
-adjacent-headers:0.020000:0.000000
-amp-in-url:0.020000:0.000000
-ampersand:0.010000:0.000000
-arabic:0.110000:0.000000
-attributes2:0.020000:0.000000
-bidi:0.310000:0.000000
-blank-block-quote:0.010000:0.000000
-blockquote:0.090000:0.000000
-blockquote-hr:0.060000:0.000000
-bold_links:0.020000:0.000000
-br:0.040000:0.000000
-bracket_re:7.490000:0.000000
-code-first-line:0.020000:0.000000
-comments:0.040000:0.000000
-div:0.040000:0.000000
-email:0.030000:0.000000
-funky-list:0.060000:0.000000
-h1:0.040000:0.000000
-hash:0.040000:0.000000
-headers:0.060000:0.000000
-hline:0.020000:0.000000
-html:0.090000:0.000000
-image:0.040000:0.000000
-image-2:0.060000:0.000000
-image_in_links:0.060000:0.000000
-inside_html:0.040000:0.000000
-japanese:0.150000:0.000000
-lazy-block-quote:0.050000:0.000000
-lists:0.110000:0.000000
-lists2:0.040000:0.000000
-lists3:0.040000:0.000000
-lists4:0.050000:0.000000
-lists5:0.070000:0.000000
-markup-inside-p:0.080000:0.000000
-mismatched-tags:0.070000:0.000000
-more_comments:0.060000:0.000000
-multi-line-tags:0.080000:0.000000
-multi-paragraph-block-quote:0.070000:0.000000
-multi-test:0.150000:0.000000
-multiline-comments:0.090000:0.000000
-normalize:0.060000:0.000000
-numeric-entity:0.090000:0.000000
-php:0.080000:0.000000
-pre:0.080000:0.000000
-russian:0.200000:0.000000
-some-test:0.200000:0.000000
-span:0.140000:0.000000
-strong-with-underscores:0.090000:0.000000
-stronintags:0.160000:0.000000
-tabs-in-lists:0.170000:0.000000
-two-spaces:0.160000:0.000000
-uche:0.150000:0.000000
-underscores:0.120000:0.000000
-url_spaces:0.120000:0.000000
+++ /dev/null
-<HTTP://WWW.SOMEURL.COM>
-
-<hr@company.com>
\ No newline at end of file
+++ /dev/null
-<p><a href="HTTP://WWW.SOMEURL.COM">HTTP://WWW.SOMEURL.COM</a></p>
-
-<p><a href="mailto:hr@company.com">hr@company.com</a></p>
\ No newline at end of file
+++ /dev/null
-Tricky combinaisons:\r\rbackslash with \\-- two dashes\r\rbackslash with \\> greater than\r\r\\\[test](not a link)\r\r\\\*no emphasis*
\ No newline at end of file
+++ /dev/null
-<p>Tricky combinaisons:</p>\r\r<p>backslash with \-- two dashes</p>\r\r<p>backslash with \> greater than</p>\r\r<p>\[test](not a link)</p>\r\r<p>\*no emphasis*</p>\r
\ No newline at end of file
+++ /dev/null
-From `<!--` to `-->`
-on two lines.
-
-From `<!--`
-to `-->`
-on three lines.
+++ /dev/null
-<p>From <code><!--</code> to <code>--></code>
-on two lines.</p>
-
-<p>From <code><!--</code>
-to <code>--></code>
-on three lines.</p>
+++ /dev/null
-
-* List Item:
-
- code block
-
- with a blank line
-
- within a list item.
-
-* code block
- as first element of a list item
-
-* List Item:
-
- code block with whitespace on preceding line
\ No newline at end of file
+++ /dev/null
-<ul>
-<li><p>List Item:</p>
-
-<pre><code>code block
-
-with a blank line
-</code></pre>
-
-<p>within a list item.</p></li>
-<li><pre><code>code block
-as first element of a list item
-</code></pre></li>
-
-<li><p>List Item:</p>
-
-<pre><code>code block with whitespace on preceding line
-</code></pre></li>
-</ul>
\ No newline at end of file
+++ /dev/null
-
- Codeblock on second line
+++ /dev/null
-<pre><code>Codeblock on second line
-</code></pre>
+++ /dev/null
-<michel.fortin@michelf.com>
-
-International domain names: <help@tūdaliņ.lv>
\ No newline at end of file
+++ /dev/null
-<p><a href="mailto:michel.fortin@michelf.com">michel.fortin@michelf.com</a></p>
-
-<p>International domain names: <a href="mailto:help@tūdaliņ.lv">help@tūdaliņ.lv</a></p>
+++ /dev/null
-Combined emphasis:
-
-1. ***test test***
-2. ___test test___
-3. *test **test***
-4. **test *test***
-5. ***test* test**
-6. ***test** test*
-7. ***test* test**
-8. **test *test***
-9. *test **test***
-10. _test __test___
-11. __test _test___
-12. ___test_ test__
-13. ___test__ test_
-14. ___test_ test__
-15. __test _test___
-16. _test __test___
-
-
-Incorrect nesting:
-
-1. *test **test* test**
-2. _test __test_ test__
-3. **test *test** test*
-4. __test _test__ test_
-5. *test *test* test*
-6. _test _test_ test_
-7. **test **test** test**
-8. __test __test__ test__
-
-
-
-No emphasis:
-
-1. test* test *test
-2. test** test **test
-3. test_ test _test
-4. test__ test __test
-
-
-
-Middle-word emphasis (asterisks):
-
-1. *a*b
-2. a*b*
-3. a*b*c
-4. **a**b
-5. a**b**
-6. a**b**c
-
-
-Middle-word emphasis (underscore):
-
-1. _a_b
-2. a_b_
-3. a_b_c
-4. __a__b
-5. a__b__
-6. a__b__c
-
-my_precious_file.txt
-
-
-## Tricky Cases
-
-E**. **Test** TestTestTest
-
-E**. **Test** Test Test Test
-
-
-## Overlong emphasis
-
-Name: ____________
-Organization: ____
-Region/Country: __
-
-_____Cut here_____
-
-____Cut here____
+++ /dev/null
-<p>Combined emphasis:</p>
-
-<ol>
-<li><strong><em>test test</em></strong></li>
-<li><strong><em>test test</em></strong></li>
-<li><em>test <strong>test</strong></em></li>
-<li><strong>test <em>test</em></strong></li>
-<li><strong><em>test</em> test</strong></li>
-<li><em><strong>test</strong> test</em></li>
-<li><strong><em>test</em> test</strong></li>
-<li><strong>test <em>test</em></strong></li>
-<li><em>test <strong>test</strong></em></li>
-<li><em>test <strong>test</strong></em></li>
-<li><strong>test <em>test</em></strong></li>
-<li><strong><em>test</em> test</strong></li>
-<li><em><strong>test</strong> test</em></li>
-<li><strong><em>test</em> test</strong></li>
-<li><strong>test <em>test</em></strong></li>
-<li><em>test <strong>test</strong></em></li>
-</ol>
-
-<p>Incorrect nesting:</p>
-
-<ol>
-<li>*test <strong>test* test</strong></li>
-<li>_test <strong>test_ test</strong></li>
-<li><strong>test *test</strong> test*</li>
-<li><strong>test _test</strong> test_</li>
-<li><em>test *test</em> test*</li>
-<li><em>test _test</em> test_</li>
-<li><strong>test **test</strong> test**</li>
-<li><strong>test __test</strong> test__</li>
-</ol>
-
-<p>No emphasis:</p>
-
-<ol>
-<li>test* test *test</li>
-<li>test** test **test</li>
-<li>test_ test _test</li>
-<li>test__ test __test</li>
-</ol>
-
-<p>Middle-word emphasis (asterisks):</p>
-
-<ol>
-<li><em>a</em>b</li>
-<li>a<em>b</em></li>
-<li>a<em>b</em>c</li>
-<li><strong>a</strong>b</li>
-<li>a<strong>b</strong></li>
-<li>a<strong>b</strong>c</li>
-</ol>
-
-<p>Middle-word emphasis (underscore):</p>
-
-<ol>
-<li><em>a</em>b</li>
-<li>a<em>b</em></li>
-<li>a<em>b</em>c</li>
-<li><strong>a</strong>b</li>
-<li>a<strong>b</strong></li>
-<li>a<strong>b</strong>c</li>
-</ol>
-
-<p>my<em>precious</em>file.txt</p>
-
-<h2>Tricky Cases</h2>
-
-<p>E**. <strong>Test</strong> TestTestTest</p>
-
-<p>E**. <strong>Test</strong> Test Test Test</p>
-
-
-<h2>Overlong emphasis</h2>
-
-<p>Name: ____________<br />
-Organization: ____<br />
-Region/Country: __</p>
-
-<p>_____Cut here_____</p>
-
-<p>____Cut here____</p>
\ No newline at end of file
+++ /dev/null
-With asterisks
-
- * List item
- *
- * List item
-
-With numbers
-
-1. List item
-2.
-3. List item
-
-With hyphens
-
-- List item
--
-- List item
-
-With asterisks
-
- * List item
- * List item
- *
-
-With numbers
-
-1. List item
-2. List item
-3.
-
-With hyphens
-
-- List item
-- List item
--
+++ /dev/null
-<p>With asterisks</p>
-
-<ul>
-<li>List item</li>
-<li></li>
-<li>List item</li>
-</ul>
-
-<p>With numbers</p>
-
-<ol>
-<li>List item</li>
-<li></li>
-<li>List item</li>
-</ol>
-
-<p>With hyphens</p>
-
-<ul>
-<li>List item</li>
-<li></li>
-<li>List item</li>
-</ul>
-
-<p>With asterisks</p>
-
-<ul>
-<li>List item</li>
-<li>List item</li>
-<li></li>
-</ul>
-
-<p>With numbers</p>
-
-<ol>
-<li>List item</li>
-<li>List item</li>
-<li></li>
-</ol>
-
-<p>With hyphens</p>
-
-<ul>
-<li>List item</li>
-<li>List item</li>
-<li></li>
-</ul>
\ No newline at end of file
+++ /dev/null
-Header\r======\r\rHeader\r------\r\r### Header
-
- - - -
-
-Header\r======\rParagraph\r\rHeader\r------\rParagraph\r\r### Header\rParagraph
-
- - - -
-
-Paragraph\rHeader\r======\rParagraph\r\rParagraph\rHeader\r------\rParagraph\r\rParagraph\r### Header\rParagraph
\ No newline at end of file
+++ /dev/null
-<h1>Header</h1>
-
-<h2>Header</h2>
-
-<h3>Header</h3>
-
-<hr />
-
-<h1>Header</h1>
-
-<p>Paragraph</p>
-
-<h2>Header</h2>
-
-<p>Paragraph</p>
-
-<h3>Header</h3>
-
-<p>Paragraph</p>
-
-<hr />
-
-<p>Paragraph</p>
-
-<h1>Header</h1>
-
-<p>Paragraph</p>
-
-<p>Paragraph</p>
-
-<h2>Header</h2>
-
-<p>Paragraph</p>
-
-<p>Paragraph</p>
-
-<h3>Header</h3>
-
-<p>Paragraph</p>
+++ /dev/null
-Horizontal rules:
-
-- - -
-
-* * *
-
-***
-
----
-
-___
-
-Not horizontal rules (testing for a bug in 1.0.1j):
-
-+++
-
-,,,
-
-===
-
-???
-
-AAA
-
-jjj
-
-j j j
-
-n n n
+++ /dev/null
-<p>Horizontal rules:</p>
-
-<hr />
-
-<hr />
-
-<hr />
-
-<hr />
-
-<hr />
-
-<p>Not horizontal rules (testing for a bug in 1.0.1j):</p>
-
-<p>+++</p>
-
-<p>,,,</p>
-
-<p>===</p>
-
-<p>???</p>
-
-<p>AAA</p>
-
-<p>jjj</p>
-
-<p>j j j</p>
-
-<p>n n n</p>
-
+++ /dev/null
-With some attributes:
-
-<div id="test">
- foo
-</div>
-
-<div id="test"
- class="nono">
- foo
-</div>
-
-Hr's:
-
-<hr class="foo"
- id="bar" >
+++ /dev/null
-<p>With some attributes:</p>
-
-<div id="test">
- foo
-</div>
-
-<div id="test"
- class="nono">
- foo
-</div>
-
-<p>Hr's:</p>
-
-<hr class="foo"
- id="bar" >
\ No newline at end of file
+++ /dev/null
-<abbr title="` **Attribute Content Is Not A Code Span** `">ACINACS</abbr>
-
-<abbr title="`first backtick!">SB</abbr>
-<abbr title="`second backtick!">SB</abbr>
\ No newline at end of file
+++ /dev/null
-<p><abbr title="` **Attribute Content Is Not A Code Span** `">ACINACS</abbr></p>
-
-<p><abbr title="`first backtick!">SB</abbr>
-<abbr title="`second backtick!">SB</abbr></p>
\ No newline at end of file
+++ /dev/null
-Paragraph one.
-
-<!-- double--dash (invalid SGML comment) -->
-
-Paragraph two.
-
-<!-- enclosed tag </div> -->
-
-The end.
+++ /dev/null
-<p>Paragraph one.</p>
-
-<!-- double--dash (invalid SGML comment) -->
-
-<p>Paragraph two.</p>
-
-<!-- enclosed tag </div> -->
-
-<p>The end.</p>
+++ /dev/null
-Here is a block tag ins:
-
-<ins>
-<p>Some text</p>
-</ins>
-
-<ins>And here it is inside a paragraph.</ins>
-
-And here it is <ins>in the middle of</ins> a paragraph.
-
-<del>
-<p>Some text</p>
-</del>
-
-<del>And here is ins as a paragraph.</del>
-
-And here it is <del>in the middle of</del> a paragraph.
+++ /dev/null
-<p>Here is a block tag ins:</p>
-
-<ins>
-<p>Some text</p>
-</ins>
-
-<p><ins>And here it is inside a paragraph.</ins></p>
-
-<p>And here it is <ins>in the middle of</ins> a paragraph.</p>
-
-<del>
-<p>Some text</p>
-</del>
-
-<p><del>And here is ins as a paragraph.</del></p>
-
-<p>And here it is <del>in the middle of</del> a paragraph.</p>
+++ /dev/null
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along
- with this program; if not, write to the Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) year name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- <signature of Ty Coon>, 1 April 1989
- Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.
+++ /dev/null
-[silly URL w/ angle brackets](<?}]*+|&)>).
+++ /dev/null
-<p><a href="?}]*+|&)">silly URL w/ angle brackets</a>.</p>
+++ /dev/null
-# Character Escapes
-
-The MD5 value for `+` is "26b17225b626fb9238849fd60eabdf60".
-
-# HTML Blocks
-
-<p>test</p>
-
-The MD5 value for `<p>test</p>` is:
-
-6205333b793f34273d75379350b36826
\ No newline at end of file
+++ /dev/null
-<h1>Character Escapes</h1>
-
-<p>The MD5 value for <code>+</code> is "26b17225b626fb9238849fd60eabdf60".</p>
-
-<h1>HTML Blocks</h1>
-
-<p>test</p>
-
-<p>The MD5 value for <code><p>test</p></code> is:</p>
-
-<p>6205333b793f34273d75379350b36826</p>
+++ /dev/null
-* test
-+ test
-- test
-
-1. test
-2. test
-
-* test
-+ test
-- test
-
-1. test
-2. test
+++ /dev/null
-<ul>
-<li>test</li>
-<li>test</li>
-<li>test</li>
-</ul>
-
-<ol>
-<li>test</li>
-<li>test</li>
-</ol>
-
-<ul>
-<li>test</li>
-<li>test</li>
-<li>test</li>
-</ul>
-
-<ol>
-<li>test</li>
-<li>test</li>
-</ol>
+++ /dev/null
-Valid nesting:
-
-**[Link](url)**
-
-[**Link**](url)
-
-**[**Link**](url)**
-
-Invalid nesting:
-
-[[Link](url)](url)
\ No newline at end of file
+++ /dev/null
-<p>Valid nesting:</p>
-
-<p><strong><a href="url">Link</a></strong></p>
-
-<p><a href="url"><strong>Link</strong></a></p>
-
-<p><strong><a href="url"><strong>Link</strong></a></strong></p>
-
-<p>Invalid nesting:</p>
-
-<p><a href="url">[Link](url)</a></p>
+++ /dev/null
-This tests for a bug where quotes escaped by PHP when using
-`preg_replace` with the `/e` modifier must be correctly unescaped
-(hence the `_UnslashQuotes` function found only in PHP Markdown).
-
-
-
-Headers below should appear exactly as they are typed (no backslash
-added or removed).
-
-Header "quoted\" again \\""
-===========================
-
-Header "quoted\" again \\""
----------------------------
-
-### Header "quoted\" again \\"" ###
-
-
-
-Test with tabs for `_Detab`:
-
- Code 'block' with some "tabs" and "quotes"
+++ /dev/null
-<p>This tests for a bug where quotes escaped by PHP when using
-<code>preg_replace</code> with the <code>/e</code> modifier must be correctly unescaped
-(hence the <code>_UnslashQuotes</code> function found only in PHP Markdown).</p>
-
-<p>Headers below should appear exactly as they are typed (no backslash
-added or removed).</p>
-
-<h1>Header "quoted\" again \""</h1>
-
-<h2>Header "quoted\" again \""</h2>
-
-<h3>Header "quoted\" again \""</h3>
-
-<p>Test with tabs for <code>_Detab</code>:</p>
-
-<pre><code>Code 'block' with some "tabs" and "quotes"
-</code></pre>
+++ /dev/null
-[Inline link 1 with parens](/url\(test\) "title").
-
-[Inline link 2 with parens](</url\(test\)> "title").
-
-[Inline link 3 with non-escaped parens](/url(test) "title").
-
-[Inline link 4 with non-escaped parens](</url(test)> "title").
-
-[Reference link 1 with parens][1].
-
-[Reference link 2 with parens][2].
-
- [1]: /url(test) "title"
- [2]: </url(test)> "title"
+++ /dev/null
-<p><a href="/url(test)" title="title">Inline link 1 with parens</a>.</p>
-
-<p><a href="/url(test)" title="title">Inline link 2 with parens</a>.</p>
-
-<p><a href="/url(test)" title="title">Inline link 3 with non-escaped parens</a>.</p>
-
-<p><a href="/url(test)" title="title">Inline link 4 with non-escaped parens</a>.</p>
-
-<p><a href="/url(test)" title="title">Reference link 1 with parens</a>.</p>
-
-<p><a href="/url(test)" title="title">Reference link 2 with parens</a>.</p>
\ No newline at end of file
+++ /dev/null
-[Test](/"style="color:red)
-[Test](/'style='color:red)
-
-
-
+++ /dev/null
-<p><a href="/"style="color:red">Test</a>
-<a href="/'style='color:red">Test</a></p>
-
-<p><img src="/"style="border-color:red;border-size:1px;border-style:solid" alt="" />
-<img src="/'style='border-color:red;border-size:1px;border-style:solid" alt="" /></p>
+++ /dev/null
-Paragraph and no space:\r* ciao\r\rParagraph and 1 space:\r * ciao\r\rParagraph and 3 spaces:\r * ciao\r\rParagraph and 4 spaces:\r * ciao\r\rParagraph before header:\r#Header\r\rParagraph before blockquote:\r>Some quote.\r
\ No newline at end of file
+++ /dev/null
-<p>Paragraph and no space:
-* ciao</p>
-
-<p>Paragraph and 1 space:
- * ciao</p>
-
-<p>Paragraph and 3 spaces:
- * ciao</p>
-
-<p>Paragraph and 4 spaces:
- * ciao</p>
-
-<p>Paragraph before header:</p>
-
-<h1>Header</h1>
-
-<p>Paragraph before blockquote:</p>
-
-<blockquote>
- <p>Some quote.</p>
-</blockquote>
+++ /dev/null
-Some text about HTML, SGML and HTML4.
-
-Let's talk about the U.S.A., (É.U. or É.-U. d'A. in French).
-
-*[HTML4]: Hyper Text Markup Language version 4
-*[HTML]: Hyper Text Markup Language
-*[SGML]: Standard Generalized Markup Language
-*[U.S.A.]: United States of America
-*[É.U.] : États-Unis d'Amérique
-*[É.-U. d'A.] : États-Unis d'Amérique
-
-And here we have a CD, some CDs, and some other CD's.
-
-*[CD]: Compact Disk
-
-Let's transfert documents through TCP/IP, using TCP packets.
-
-*[IP]: Internet Protocol
-*[TCP]: Transmission Control Protocol
-
- ---
-
-Bienvenue sur [CMS](http://www.bidulecms.com "Bidule CMS").
-
-*[CMS]: Content Management System
-
- ---
-
-ATCCE
-
-*[ATCCE]: Abbreviation "Testing" Correct 'Character' < Escapes >
\ No newline at end of file
+++ /dev/null
-<p>Some text about <abbr title="Hyper Text Markup Language">HTML</abbr>, <abbr title="Standard Generalized Markup Language">SGML</abbr> and <abbr title="Hyper Text Markup Language version 4">HTML4</abbr>.</p>
-
-<p>Let's talk about the <abbr title="United States of America">U.S.A.</abbr>, (<abbr title="États-Unis d'Amérique">É.U.</abbr> or <abbr title="États-Unis d'Amérique">É.-U. d'A.</abbr> in French).</p>
-
-<p>And here we have a <abbr title="Compact Disk">CD</abbr>, some CDs, and some other <abbr title="Compact Disk">CD</abbr>'s.</p>
-
-<p>Let's transfert documents through <abbr title="Transmission Control Protocol">TCP</abbr>/<abbr title="Internet Protocol">IP</abbr>, using <abbr title="Transmission Control Protocol">TCP</abbr> packets.</p>
-
-<hr />
-
-<p>Bienvenue sur <a href="http://www.bidulecms.com" title="Bidule CMS"><abbr title="Content Management System">CMS</abbr></a>.</p>
-
-<hr />
-
-<p><abbr title="Abbreviation "Testing" Correct 'Character' < Escapes >">ATCCE</abbr></p>
+++ /dev/null
-A simple definition list:
-
-Term 1
-: Definition 1
-
-Term 2
-: Definition 2
-
-With multiple terms:
-
-Term 1
-Term 2
-: Definition 1
-
-Term 3
-Term 4
-: Definition 2
-
-With multiple definitions:
-
-Term 1
-: Definition 1
-: Definition 2
-
-Term 2
-: Definition 3
-: Definition 4
-
-With multiple lines per definition:
-
-Term 1
-: Definition 1 line 1 ...
-Definition 1 line 2
-: Definition 2 line 1 ...
-Definition 2 line 2
-
-Term 2
-: Definition 3 line 2 ...
- Definition 3 line 2
-: Definition 4 line 2 ...
- Definition 4 line 2
-
-With paragraphs:
-
-Term 1
-
-: Definition 1 (paragraph)
-
-Term 2
-
-: Definition 2 (paragraph)
-
-With multiple paragraphs:
-
-Term 1
-
-: Definition 1 paragraph 1 line 1 ...
- Definition 1 paragraph 1 line 2
-
- Definition 1 paragraph 2 line 1 ...
- Definition 1 paragraph 2 line 2
-
-Term 2
-
-: Definition 1 paragraph 1 line 1 ...
-Definition 1 paragraph 1 line 2 (lazy)
-
- Definition 1 paragraph 2 line 1 ...
-Definition 1 paragraph 2 line 2 (lazy)
-
-* * *
-
-A mix:
-
-Term 1
-Term 2
-
-: Definition 1 paragraph 1 line 1 ...
-Definition 1 paragraph 1 line 2 (lazy)
-
- Definition 1 paragraph 2 line 1 ...
- Definition 1 paragraph 2 line 2
-
-: Definition 2 paragraph 1 line 1 ...
-Definition 2 paragraph 1 line 2 (lazy)
-
-Term 3
-: Definition 3 (no paragraph)
-: Definition 4 (no paragraph)
-: Definition 5 line 1 ...
- Definition 5 line 2 (no paragraph)
-
-: Definition 6 paragraph 1 line 1 ...
-Definition 6 paragraph 1 line 2
-: Definition 7 (no paragraph)
-: Definition 8 paragraph 1 line 1 (forced paragraph) ...
- Definition 8 paragraph 1 line 2
-
- Definition 8 paragraph 2 line 1
-
-Term 4
-: Definition 9 paragraph 1 line 1 (forced paragraph) ...
- Definition 9 paragraph 1 line 2
-
- Definition 9 paragraph 2 line 1
-: Definition 10 (no paragraph)
-
-* * *
-
-Special cases:
-
-Term
-
-: code block
- as first element of a definition
\ No newline at end of file
+++ /dev/null
-<p>A simple definition list:</p>
-
-<dl>
-<dt>Term 1</dt>
-<dd>Definition 1</dd>
-
-<dt>Term 2</dt>
-<dd>Definition 2</dd>
-</dl>
-
-<p>With multiple terms:</p>
-
-<dl>
-<dt>Term 1</dt>
-<dt>Term 2</dt>
-<dd>Definition 1</dd>
-
-<dt>Term 3</dt>
-<dt>Term 4</dt>
-<dd>Definition 2</dd>
-</dl>
-
-<p>With multiple definitions:</p>
-
-<dl>
-<dt>Term 1</dt>
-<dd>Definition 1</dd>
-
-<dd>Definition 2</dd>
-
-<dt>Term 2</dt>
-<dd>Definition 3</dd>
-
-<dd>Definition 4</dd>
-</dl>
-
-<p>With multiple lines per definition:</p>
-
-<dl>
-<dt>Term 1</dt>
-<dd>Definition 1 line 1 ...
-Definition 1 line 2</dd>
-
-<dd>Definition 2 line 1 ...
-Definition 2 line 2</dd>
-
-<dt>Term 2</dt>
-<dd>Definition 3 line 2 ...
-Definition 3 line 2</dd>
-
-<dd>Definition 4 line 2 ...
-Definition 4 line 2</dd>
-</dl>
-
-<p>With paragraphs:</p>
-
-<dl>
-<dt>Term 1</dt>
-<dd>
-<p>Definition 1 (paragraph)</p>
-</dd>
-
-<dt>Term 2</dt>
-<dd>
-<p>Definition 2 (paragraph)</p>
-</dd>
-</dl>
-
-<p>With multiple paragraphs:</p>
-
-<dl>
-<dt>Term 1</dt>
-<dd>
-<p>Definition 1 paragraph 1 line 1 ...
-Definition 1 paragraph 1 line 2</p>
-
-<p>Definition 1 paragraph 2 line 1 ...
-Definition 1 paragraph 2 line 2</p>
-</dd>
-
-<dt>Term 2</dt>
-<dd>
-<p>Definition 1 paragraph 1 line 1 ...
-Definition 1 paragraph 1 line 2 (lazy)</p>
-
-<p>Definition 1 paragraph 2 line 1 ...
-Definition 1 paragraph 2 line 2 (lazy)</p>
-</dd>
-</dl>
-
-<hr />
-
-<p>A mix:</p>
-
-<dl>
-<dt>Term 1</dt>
-<dt>Term 2</dt>
-<dd>
-<p>Definition 1 paragraph 1 line 1 ...
-Definition 1 paragraph 1 line 2 (lazy)</p>
-
-<p>Definition 1 paragraph 2 line 1 ...
-Definition 1 paragraph 2 line 2</p>
-</dd>
-
-<dd>
-<p>Definition 2 paragraph 1 line 1 ...
-Definition 2 paragraph 1 line 2 (lazy)</p>
-</dd>
-
-<dt>Term 3</dt>
-<dd>Definition 3 (no paragraph)</dd>
-
-<dd>Definition 4 (no paragraph)</dd>
-
-<dd>Definition 5 line 1 ...
-Definition 5 line 2 (no paragraph)</dd>
-
-<dd>
-<p>Definition 6 paragraph 1 line 1 ...
-Definition 6 paragraph 1 line 2</p>
-</dd>
-
-<dd>Definition 7 (no paragraph)</dd>
-
-<dd>
-<p>Definition 8 paragraph 1 line 1 (forced paragraph) ...
-Definition 8 paragraph 1 line 2</p>
-
-<p>Definition 8 paragraph 2 line 1</p>
-</dd>
-
-<dt>Term 4</dt>
-<dd>
-<p>Definition 9 paragraph 1 line 1 (forced paragraph) ...
-Definition 9 paragraph 1 line 2</p>
-
-<p>Definition 9 paragraph 2 line 1</p>
-</dd>
-
-<dd>Definition 10 (no paragraph)</dd>
-</dl>
-
-<hr />
-
-<p>Special cases:</p>
-
-<dl>
-<dt>Term</dt>
-<dd>
-<pre><code>code block
-as first element of a definition
-</code></pre>
-</dd>
-</dl>
+++ /dev/null
-Combined emphasis:
-
-1. ***test test***
-2. ___test test___
-3. *test **test***
-4. **test *test***
-5. ***test* test**
-6. ***test** test*
-7. ***test* test**
-8. **test *test***
-9. *test **test***
-10. _test __test___
-11. __test _test___
-12. ___test_ test__
-13. ___test__ test_
-14. ___test_ test__
-15. __test _test___
-16. _test __test___
-
-
-Incorrect nesting:
-
-1. *test **test* test**
-2. _test __test_ test__
-3. **test *test** test*
-4. __test _test__ test_
-5. *test *test* test*
-6. _test _test_ test_
-7. **test **test** test**
-8. __test __test__ test__
-
-
-
-No emphasis:
-
-1. test* test *test
-2. test** test **test
-3. test_ test _test
-4. test__ test __test
-
-
-
-Middle-word emphasis (asterisks):
-
-1. *a*b
-2. a*b*
-3. a*b*c
-4. **a**b
-5. a**b**
-6. a**b**c
-
-
-Middle-word emphasis (underscore):
-
-1. _a_b
-2. a_b_
-3. a_b_c
-4. __a__b
-5. a__b__
-6. a__b__c
-
-my_precious_file.txt
-
-
-## Tricky Cases
-
-E**. **Test** TestTestTest
-
-E**. **Test** Test Test Test
-
-
-## Overlong emphasis
-
-Name: ____________
-Organization: ____
-Region/Country: __
-
-_____Cut here_____
-
-____Cut here____
+++ /dev/null
-<p>Combined emphasis:</p>
-
-<ol>
-<li><strong><em>test test</em></strong></li>
-<li><strong><em>test test</em></strong></li>
-<li><em>test <strong>test</strong></em></li>
-<li><strong>test <em>test</em></strong></li>
-<li><strong><em>test</em> test</strong></li>
-<li><em><strong>test</strong> test</em></li>
-<li><strong><em>test</em> test</strong></li>
-<li><strong>test <em>test</em></strong></li>
-<li><em>test <strong>test</strong></em></li>
-<li><em>test <strong>test</strong></em></li>
-<li><strong>test <em>test</em></strong></li>
-<li><strong><em>test</em> test</strong></li>
-<li><em><strong>test</strong> test</em></li>
-<li><strong><em>test</em> test</strong></li>
-<li><strong>test <em>test</em></strong></li>
-<li><em>test <strong>test</strong></em></li>
-</ol>
-
-<p>Incorrect nesting:</p>
-
-<ol>
-<li>*test <strong>test* test</strong></li>
-<li>_test <strong>test_ test</strong></li>
-<li><strong>test *test</strong> test*</li>
-<li><strong>test _test</strong> test_</li>
-<li><em>test *test</em> test*</li>
-<li><em>test _test</em> test_</li>
-<li><strong>test **test</strong> test**</li>
-<li><strong>test __test</strong> test__</li>
-</ol>
-
-<p>No emphasis:</p>
-
-<ol>
-<li>test* test *test</li>
-<li>test** test **test</li>
-<li>test_ test _test</li>
-<li>test__ test __test</li>
-</ol>
-
-<p>Middle-word emphasis (asterisks):</p>
-
-<ol>
-<li><em>a</em>b</li>
-<li>a<em>b</em></li>
-<li>a<em>b</em>c</li>
-<li><strong>a</strong>b</li>
-<li>a<strong>b</strong></li>
-<li>a<strong>b</strong>c</li>
-</ol>
-
-<p>Middle-word emphasis (underscore):</p>
-
-<ol>
-<li>_a_b</li>
-<li>a_b_</li>
-<li>a_b_c</li>
-<li>__a__b</li>
-<li>a__b__</li>
-<li>a__b__c</li>
-</ol>
-
-<p>my_precious_file.txt</p>
-
-<h2>Tricky Cases</h2>
-
-<p>E**. <strong>Test</strong> TestTestTest</p>
-
-<p>E**. <strong>Test</strong> Test Test Test</p>
-
-
-<h2>Overlong emphasis</h2>
-
-<p>Name: ____________<br />
-Organization: ____<br />
-Region/Country: __</p>
-
-<p>_____Cut here_____</p>
-
-<p>____Cut here____</p>
+++ /dev/null
-~~~
-Fenced
-~~~
-
-Code block starting and ending with empty lines:
-~~~
-
-
-Fenced
-
-
-~~~
-
-Indented code block containing fenced code block sample:
-
- ~~~
- Fenced
- ~~~
-
-Fenced code block with indented code block sample:
-
-~~~
-Some text
-
- Indented code block sample code
-~~~
-
-Fenced code block with long markers:
-
-~~~~~~~~~~~~~~~~~~
-Fenced
-~~~~~~~~~~~~~~~~~~
-
-Fenced code block with fenced code block markers of different length in it:
-
-~~~~
-In code block
-~~~
-Still in code block
-~~~~~
-Still in code block
-~~~~
-
-Fenced code block with Markdown header and horizontal rule:
-
-~~~
-#test
----
-~~~
-
-Fenced code block with link definitions, footnote definition and
-abbreviation definitions:
-
-~~~
-[example]: http://example.com/
-
-[^1]: Footnote def
-
-*[HTML]: HyperText Markup Language
-~~~
\ No newline at end of file
+++ /dev/null
-<pre><code>Fenced
-</code></pre>
-
-<p>Code block starting and ending with empty lines:</p>
-
-<pre><code><br /><br />Fenced
-
-
-</code></pre>
-
-<p>Indented code block containing fenced code block sample:</p>
-
-<pre><code>~~~
-Fenced
-~~~
-</code></pre>
-
-<p>Fenced code block with indented code block sample:</p>
-
-<pre><code>Some text
-
- Indented code block sample code
-</code></pre>
-
-<p>Fenced code block with long markers:</p>
-
-<pre><code>Fenced
-</code></pre>
-
-<p>Fenced code block with fenced code block markers of different length in it:</p>
-
-<pre><code>In code block
-~~~
-Still in code block
-~~~~~
-Still in code block
-</code></pre>
-
-<p>Fenced code block with Markdown header and horizontal rule:</p>
-
-<pre><code>#test
----
-</code></pre>
-
-<p>Fenced code block with link definitions, footnote definition and
-abbreviation definitions:</p>
-
-<pre><code>[example]: http://example.com/
-
-[^1]: Footnote def
-
-*[HTML]: HyperText Markup Language
-</code></pre>
+++ /dev/null
-This is the first paragraph.[^first]
-
-[^first]: This is the first note.
-
-* List item one.[^second]
-* List item two.[^third]
-
-[^third]: This is the third note, defined out of order.
-[^second]: This is the second note.
-[^fourth]: This is the fourth note.
-
-# Header[^fourth]
-
-Some paragraph with a footnote[^1], and another[^2].
-
-[^1]: Content for fifth footnote.
-[^2]: Content for sixth footnote spaning on
- three lines, with some span-level markup like
- _emphasis_, a [link][].
-
-[link]: http://www.michelf.com/
-
-Another paragraph with a named footnote[^fn-name].
-
-[^fn-name]:
- Footnote beginning on the line next to the marker.
-
-This paragraph should not have a footnote marker since
-the footnote is undefined.[^3]
-
-This paragraph should not have a footnote marker since
-the footnote has already been used before.[^1]
-
-This paragraph links to a footnote with plenty of
-block-level content.[^block]
-
-[^block]:
- Paragraph.
-
- * List item
-
- > Blockquote
-
- Code block
-
-This paragraph host the footnote reference within a
-footnote test[^reference].
-
-[^reference]:
- This footnote has a footnote of its own.[^nested]
-
-[^nested]:
- This footnote should appear even though as it is refered
- from another footnote. But [^reference] should be litteral
- since the footnote with that name has already been used.
-
- - - -
-
-Testing unusual footnote name[^1$^!"'].
-
-[^1$^!"']: Haha!
+++ /dev/null
-<p>This is the first paragraph.<sup id="fnref:first"><a href="#fn:first" rel="footnote">1</a></sup></p>
-
-<ul>
-<li>List item one.<sup id="fnref:second"><a href="#fn:second" rel="footnote">2</a></sup></li>
-<li>List item two.<sup id="fnref:third"><a href="#fn:third" rel="footnote">3</a></sup></li>
-</ul>
-
-<h1>Header<sup id="fnref:fourth"><a href="#fn:fourth" rel="footnote">4</a></sup></h1>
-
-<p>Some paragraph with a footnote<sup id="fnref:1"><a href="#fn:1" rel="footnote">5</a></sup>, and another<sup id="fnref:2"><a href="#fn:2" rel="footnote">6</a></sup>.</p>
-
-<p>Another paragraph with a named footnote<sup id="fnref:fn-name"><a href="#fn:fn-name" rel="footnote">7</a></sup>.</p>
-
-<p>This paragraph should not have a footnote marker since
-the footnote is undefined.[^3]</p>
-
-<p>This paragraph should not have a footnote marker since
-the footnote has already been used before.[^1]</p>
-
-<p>This paragraph links to a footnote with plenty of
-block-level content.<sup id="fnref:block"><a href="#fn:block" rel="footnote">8</a></sup></p>
-
-<p>This paragraph host the footnote reference within a
-footnote test<sup id="fnref:reference"><a href="#fn:reference" rel="footnote">9</a></sup>.</p>
-
-<hr />
-
-<p>Testing unusual footnote name<sup id="fnref:1$^!"'"><a href="#fn:1$^!"'" rel="footnote">10</a></sup>.</p>
-
-<div class="footnotes">
-<hr />
-<ol>
-
-<li id="fn:first">
-<p>This is the first note. <a href="#fnref:first" rev="footnote">↩</a></p>
-</li>
-
-<li id="fn:second">
-<p>This is the second note. <a href="#fnref:second" rev="footnote">↩</a></p>
-</li>
-
-<li id="fn:third">
-<p>This is the third note, defined out of order. <a href="#fnref:third" rev="footnote">↩</a></p>
-</li>
-
-<li id="fn:fourth">
-<p>This is the fourth note. <a href="#fnref:fourth" rev="footnote">↩</a></p>
-</li>
-
-<li id="fn:1">
-<p>Content for fifth footnote. <a href="#fnref:1" rev="footnote">↩</a></p>
-</li>
-
-<li id="fn:2">
-<p>Content for sixth footnote spaning on
-three lines, with some span-level markup like
-<em>emphasis</em>, a <a href="http://www.michelf.com/">link</a>. <a href="#fnref:2" rev="footnote">↩</a></p>
-</li>
-
-<li id="fn:fn-name">
-<p>Footnote beginning on the line next to the marker. <a href="#fnref:fn-name" rev="footnote">↩</a></p>
-</li>
-
-<li id="fn:block">
-<p>Paragraph.</p>
-
-<ul>
-<li>List item</li>
-</ul>
-
-<blockquote>
- <p>Blockquote</p>
-</blockquote>
-
-<pre><code>Code block
-</code></pre>
-
-<p><a href="#fnref:block" rev="footnote">↩</a></p>
-</li>
-
-<li id="fn:reference">
-<p>This footnote has a footnote of its own.<sup id="fnref:nested"><a href="#fn:nested" rel="footnote">11</a></sup> <a href="#fnref:reference" rev="footnote">↩</a></p>
-</li>
-
-<li id="fn:1$^!"'">
-<p>Haha! <a href="#fnref:1$^!"'" rev="footnote">↩</a></p>
-</li>
-
-<li id="fn:nested">
-<p>This footnote should appear even though as it is refered
-from another footnote. But [^reference] should be litteral
-since the footnote with that name has already been used. <a href="#fnref:nested" rev="footnote">↩</a></p>
-</li>
-
-</ol>
-</div>
+++ /dev/null
-# Markdown inside code blocks
-
-<div markdown="1">
-foo
-</div>
-
-<div markdown='1'>
-foo
-</div>
-
-<div markdown=1>
-foo
-</div>
-
-<table>
-<tr><td markdown="1">test _emphasis_ (span)</td></tr>
-</table>
-
-<table>
-<tr><td markdown="span">test _emphasis_ (span)</td></tr>
-</table>
-
-<table>
-<tr><td markdown="block">test _emphasis_ (block)</td></tr>
-</table>
-
-## More complicated
-
-<table>
-<tr><td markdown="1">
-* this is _not_ a list item</td></tr>
-<tr><td markdown="span">
-* this is _not_ a list item</td></tr>
-<tr><td markdown="block">
-* this _is_ a list item
-</td></tr>
-</table>
-
-## With indent
-
-<div>
- <div markdown="1">
- This text is no code block: if it was, the
- closing `<div>` would be too and the HTML block
- would be invalid.
-
- Markdown content in HTML blocks is assumed to be
- indented the same as the block opening tag.
-
- **This should be the third paragraph after the header.**
- </div>
-</div>
-
-## Code block with rogue `</div>`s in Markdown code span and block
-
-<div>
- <div markdown="1">
-
- This is a code block however:
-
- </div>
-
- Funny isn't it? Here is a code span: `</div>`.
-
- </div>
-</div>
-
-<div>
- <div markdown="1">
- * List item, not a code block
-
-Some text
-
- This is a code block.
- </div>
-</div>
-
-## No code block in markdown span mode
-
-<p markdown="1">
- This is not a code block since Markdown parse paragraph
- content as span. Code spans like `</p>` are allowed though.
-</p>
-
-<p markdown="1">_Hello_ _world_</p>
-
-## Preserving attributes and tags on more than one line:
-
-<p class="test" markdown="1"
-id="12">
-Some _span_ content.
-</p>
-
-
-## Header confusion bug
-
-<table class="canvas">
-<tr>
-<td id="main" markdown="1">Hello World!
-============
-
-Hello World!</td>
-</tr>
-</table>
+++ /dev/null
-<h1>Markdown inside code blocks</h1>
-
-<div>
-
-<p>foo</p>
-
-</div>
-
-<div>
-
-<p>foo</p>
-
-</div>
-
-<div>
-
-<p>foo</p>
-
-</div>
-
-<table>
-<tr><td>test <em>emphasis</em> (span)</td></tr>
-</table>
-
-<table>
-<tr><td>test <em>emphasis</em> (span)</td></tr>
-</table>
-
-<table>
-<tr><td>
-
-<p>test <em>emphasis</em> (block)</p>
-
-</td></tr>
-</table>
-
-<h2>More complicated</h2>
-
-<table>
-<tr><td>
-* this is <em>not</em> a list item</td></tr>
-<tr><td>
-* this is <em>not</em> a list item</td></tr>
-<tr><td>
-
-<ul>
-<li>this <em>is</em> a list item</li>
-</ul>
-
-</td></tr>
-</table>
-
-<h2>With indent</h2>
-
-<div>
- <div>
-
-<p>This text is no code block: if it was, the
-closing <code><div></code> would be too and the HTML block
-would be invalid.</p>
-
-<p>Markdown content in HTML blocks is assumed to be
-indented the same as the block opening tag.</p>
-
-<p><strong>This should be the third paragraph after the header.</strong></p>
-
-</div>
-</div>
-
-<h2>Code block with rogue <code></div></code>s in Markdown code span and block</h2>
-
-<div>
- <div>
-
-<p>This is a code block however:</p>
-
-<pre><code></div>
-</code></pre>
-
-<p>Funny isn't it? Here is a code span: <code></div></code>.</p>
-
-</div>
-</div>
-
-<div>
- <div>
-
-<ul>
-<li>List item, not a code block</li>
-</ul>
-
-<p>Some text</p>
-
-<pre><code>This is a code block.
-</code></pre>
-
-</div>
-</div>
-
-<h2>No code block in markdown span mode</h2>
-
-<p>
- This is not a code block since Markdown parse paragraph
- content as span. Code spans like <code></p></code> are allowed though.
-</p>
-
-<p><em>Hello</em> <em>world</em></p>
-
-<h2>Preserving attributes and tags on more than one line:</h2>
-
-<p class="test"
-id="12">
-Some <em>span</em> content.
-</p>
-
-<h2>Header confusion bug</h2>
-
-<table class="canvas">
-<tr>
-<td id="main">Hello World!
-============
-
-Hello World!</td>
-</tr>
-</table>
\ No newline at end of file
+++ /dev/null
-# Simple tables
-
-Header 1 | Header 2
---------- | ---------
-Cell 1 | Cell 2
-Cell 3 | Cell 4
-
-With leading pipes:
-
-| Header 1 | Header 2
-| --------- | ---------
-| Cell 1 | Cell 2
-| Cell 3 | Cell 4
-
-With tailing pipes:
-
-Header 1 | Header 2 |
---------- | --------- |
-Cell 1 | Cell 2 |
-Cell 3 | Cell 4 |
-
-With leading and tailing pipes:
-
-| Header 1 | Header 2 |
-| --------- | --------- |
-| Cell 1 | Cell 2 |
-| Cell 3 | Cell 4 |
-
-* * *
-
-# One-column one-row table
-
-With leading pipes:
-
-| Header
-| -------
-| Cell
-
-With tailing pipes:
-
-Header |
-------- |
-Cell |
-
-With leading and tailing pipes:
-
-| Header |
-| ------- |
-| Cell |
-
-* * *
-
-Table alignement:
-
-| Default | Right | Center | Left |
-| --------- |:--------- |:---------:| ---------:|
-| Long Cell | Long Cell | Long Cell | Long Cell |
-| Cell | Cell | Cell | Cell |
-
-Table alignement (alternate spacing):
-
-| Default | Right | Center | Left |
-| --------- | :-------- | :-------: | --------: |
-| Long Cell | Long Cell | Long Cell | Long Cell |
-| Cell | Cell | Cell | Cell |
-
-* * *
-
-# Empty cells
-
-| Header 1 | Header 2 |
-| --------- | --------- |
-| A | B |
-| C | |
-
-Header 1 | Header 2
---------- | ---------
-A | B
- | D
-
-* * *
-
-# Missing tailing pipe
-
-Header 1 | Header 2
---------- | --------- |
-Cell | Cell |
-Cell | Cell |
-
-Header 1 | Header 2 |
---------- | ---------
-Cell | Cell |
-Cell | Cell |
-
-Header 1 | Header 2 |
---------- | --------- |
-Cell | Cell
-Cell | Cell |
-
-Header 1 | Header 2 |
---------- | --------- |
-Cell | Cell |
-Cell | Cell
-
+++ /dev/null
-<h1>Simple tables</h1>
-
-<table>
-<thead>
-<tr>
- <th>Header 1</th>
- <th>Header 2</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>Cell 1</td>
- <td>Cell 2</td>
-</tr>
-<tr>
- <td>Cell 3</td>
- <td>Cell 4</td>
-</tr>
-</tbody>
-</table>
-
-<p>With leading pipes:</p>
-
-<table>
-<thead>
-<tr>
- <th>Header 1</th>
- <th>Header 2</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>Cell 1</td>
- <td>Cell 2</td>
-</tr>
-<tr>
- <td>Cell 3</td>
- <td>Cell 4</td>
-</tr>
-</tbody>
-</table>
-
-<p>With tailing pipes:</p>
-
-<table>
-<thead>
-<tr>
- <th>Header 1</th>
- <th>Header 2</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>Cell 1</td>
- <td>Cell 2</td>
-</tr>
-<tr>
- <td>Cell 3</td>
- <td>Cell 4</td>
-</tr>
-</tbody>
-</table>
-
-<p>With leading and tailing pipes:</p>
-
-<table>
-<thead>
-<tr>
- <th>Header 1</th>
- <th>Header 2</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>Cell 1</td>
- <td>Cell 2</td>
-</tr>
-<tr>
- <td>Cell 3</td>
- <td>Cell 4</td>
-</tr>
-</tbody>
-</table>
-
-<hr />
-
-<h1>One-column one-row table</h1>
-
-<p>With leading pipes:</p>
-
-<table>
-<thead>
-<tr>
- <th>Header</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>Cell</td>
-</tr>
-</tbody>
-</table>
-
-<p>With tailing pipes:</p>
-
-<table>
-<thead>
-<tr>
- <th>Header</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>Cell</td>
-</tr>
-</tbody>
-</table>
-
-<p>With leading and tailing pipes:</p>
-
-<table>
-<thead>
-<tr>
- <th>Header</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>Cell</td>
-</tr>
-</tbody>
-</table>
-
-<hr />
-
-<p>Table alignement:</p>
-
-<table>
-<thead>
-<tr>
- <th>Default</th>
- <th align="left">Right</th>
- <th align="center">Center</th>
- <th align="right">Left</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>Long Cell</td>
- <td align="left">Long Cell</td>
- <td align="center">Long Cell</td>
- <td align="right">Long Cell</td>
-</tr>
-<tr>
- <td>Cell</td>
- <td align="left">Cell</td>
- <td align="center">Cell</td>
- <td align="right">Cell</td>
-</tr>
-</tbody>
-</table>
-
-<p>Table alignement (alternate spacing):</p>
-
-<table>
-<thead>
-<tr>
- <th>Default</th>
- <th align="left">Right</th>
- <th align="center">Center</th>
- <th align="right">Left</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>Long Cell</td>
- <td align="left">Long Cell</td>
- <td align="center">Long Cell</td>
- <td align="right">Long Cell</td>
-</tr>
-<tr>
- <td>Cell</td>
- <td align="left">Cell</td>
- <td align="center">Cell</td>
- <td align="right">Cell</td>
-</tr>
-</tbody>
-</table>
-
-<hr />
-
-<h1>Empty cells</h1>
-
-<table>
-<thead>
-<tr>
- <th>Header 1</th>
- <th>Header 2</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>A</td>
- <td>B</td>
-</tr>
-<tr>
- <td>C</td>
- <td></td>
-</tr>
-</tbody>
-</table>
-
-<table>
-<thead>
-<tr>
- <th>Header 1</th>
- <th>Header 2</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>A</td>
- <td>B</td>
-</tr>
-<tr>
- <td></td>
- <td>D</td>
-</tr>
-</tbody>
-</table>
-
-<hr />
-
-<h1>Missing tailing pipe</h1>
-
-<table>
-<thead>
-<tr>
- <th>Header 1</th>
- <th>Header 2</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>Cell</td>
- <td>Cell</td>
-</tr>
-<tr>
- <td>Cell</td>
- <td>Cell</td>
-</tr>
-</tbody>
-</table>
-
-<table>
-<thead>
-<tr>
- <th>Header 1</th>
- <th>Header 2</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>Cell</td>
- <td>Cell</td>
-</tr>
-<tr>
- <td>Cell</td>
- <td>Cell</td>
-</tr>
-</tbody>
-</table>
-
-<table>
-<thead>
-<tr>
- <th>Header 1</th>
- <th>Header 2</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>Cell</td>
- <td>Cell</td>
-</tr>
-<tr>
- <td>Cell</td>
- <td>Cell</td>
-</tr>
-</tbody>
-</table>
-
-<table>
-<thead>
-<tr>
- <th>Header 1</th>
- <th>Header 2</th>
-</tr>
-</thead>
-<tbody>
-<tr>
- <td>Cell</td>
- <td>Cell</td>
-</tr>
-<tr>
- <td>Cell</td>
- <td>Cell</td>
-</tr>
-</tbody>
-</table>
\ No newline at end of file
+++ /dev/null
-AT&T has an ampersand in their name.
-
-AT&T is another way to write it.
-
-This & that.
-
-4 < 5.
-
-6 > 5.
-
-Here's a [link] [1] with an ampersand in the URL.
-
-Here's a link with an amersand in the link text: [AT&T] [2].
-
-Here's an inline [link](/script?foo=1&bar=2).
-
-Here's an inline [link](</script?foo=1&bar=2>).
-
-
-[1]: http://example.com/?foo=1&bar=2
-[2]: http://att.com/ "AT&T"
\ No newline at end of file
+++ /dev/null
-Link: <http://example.com/>.
-
-With an ampersand: <http://example.com/?foo=1&bar=2>
-
-* In a list?
-* <http://example.com/>
-* It should.
-
-> Blockquoted: <http://example.com/>
-
-Auto-links should not occur here: `<http://example.com/>`
-
- or here: <http://example.com/>
\ No newline at end of file
+++ /dev/null
-These should all get escaped:
-
-Backslash: \\
-
-Backtick: \`
-
-Asterisk: \*
-
-Underscore: \_
-
-Left brace: \{
-
-Right brace: \}
-
-Left bracket: \[
-
-Right bracket: \]
-
-Left paren: \(
-
-Right paren: \)
-
-Greater-than: \>
-
-Hash: \#
-
-Period: \.
-
-Bang: \!
-
-Plus: \+
-
-Minus: \-
-
-
-
-These should not, because they occur within a code block:
-
- Backslash: \\
-
- Backtick: \`
-
- Asterisk: \*
-
- Underscore: \_
-
- Left brace: \{
-
- Right brace: \}
-
- Left bracket: \[
-
- Right bracket: \]
-
- Left paren: \(
-
- Right paren: \)
-
- Greater-than: \>
-
- Hash: \#
-
- Period: \.
-
- Bang: \!
-
- Plus: \+
-
- Minus: \-
-
-
-Nor should these, which occur in code spans:
-
-Backslash: `\\`
-
-Backtick: `` \` ``
-
-Asterisk: `\*`
-
-Underscore: `\_`
-
-Left brace: `\{`
-
-Right brace: `\}`
-
-Left bracket: `\[`
-
-Right bracket: `\]`
-
-Left paren: `\(`
-
-Right paren: `\)`
-
-Greater-than: `\>`
-
-Hash: `\#`
-
-Period: `\.`
-
-Bang: `\!`
-
-Plus: `\+`
-
-Minus: `\-`
+++ /dev/null
-> Example:
->
-> sub status {
-> print "working";
-> }
->
-> Or:
->
-> sub status {
-> return "working";
-> }
+++ /dev/null
-In Markdown 1.0.0 and earlier. Version
-8. This line turns into a list item.
-Because a hard-wrapped line in the
-middle of a paragraph looked like a
-list item.
-
-Here's one with a bullet.
-* criminey.
+++ /dev/null
-Dashes:
-
----
-
- ---
-
- ---
-
- ---
-
- ---
-
-- - -
-
- - - -
-
- - - -
-
- - - -
-
- - - -
-
-
-Asterisks:
-
-***
-
- ***
-
- ***
-
- ***
-
- ***
-
-* * *
-
- * * *
-
- * * *
-
- * * *
-
- * * *
-
-
-Underscores:
-
-___
-
- ___
-
- ___
-
- ___
-
- ___
-
-_ _ _
-
- _ _ _
-
- _ _ _
-
- _ _ _
-
- _ _ _
+++ /dev/null
-Simple block on one line:
-
-<div>foo</div>
-
-And nested without indentation:
-
-<div>
-<div>
-<div>
-foo
-</div>
-</div>
-<div>bar</div>
-</div>
+++ /dev/null
-Here's a simple block:
-
-<div>
- foo
-</div>
-
-This should be a code block, though:
-
- <div>
- foo
- </div>
-
-As should this:
-
- <div>foo</div>
-
-Now, nested:
-
-<div>
- <div>
- <div>
- foo
- </div>
- </div>
-</div>
-
-This should just be an HTML comment:
-
-<!-- Comment -->
-
-Multiline:
-
-<!--
-Blah
-Blah
--->
-
-Code block:
-
- <!-- Comment -->
-
-Just plain comment, with trailing spaces on the line:
-
-<!-- foo -->
-
-Code:
-
- <hr />
-
-Hr's:
-
-<hr>
-
-<hr/>
-
-<hr />
-
-<hr>
-
-<hr/>
-
-<hr />
-
-<hr class="foo" id="bar" />
-
-<hr class="foo" id="bar"/>
-
-<hr class="foo" id="bar" >
-
+++ /dev/null
-Paragraph one.
-
-<!-- This is a simple comment -->
-
-<!--
- This is another comment.
--->
-
-Paragraph two.
-
-<!-- one comment block -- -- with two comments -->
-
-The end.
+++ /dev/null
-Just a [URL](/url/).
-
-[URL and title](/url/ "title").
-
-[URL and title](/url/ "title preceded by two spaces").
-
-[URL and title](/url/ "title preceded by a tab").
-
-[Empty]().
+++ /dev/null
-Foo [bar] [1].
-
-Foo [bar][1].
-
-Foo [bar]
-[1].
-
-[1]: /url/ "Title"
-
-
-With [embedded [brackets]] [b].
-
-
-Indented [once][].
-
-Indented [twice][].
-
-Indented [thrice][].
-
-Indented [four][] times.
-
- [once]: /url
-
- [twice]: /url
-
- [thrice]: /url
-
- [four]: /url
-
-
-[b]: /url/
+++ /dev/null
-Foo [bar][].
-
-Foo [bar](/url/ "Title with "quotes" inside").
-
-
- [bar]: /url/ "Title with "quotes" inside"
-
+++ /dev/null
-Markdown: Basics
-================
-
-<ul id="ProjectSubmenu">
- <li><a href="/projects/markdown/" title="Markdown Project Page">Main</a></li>
- <li><a class="selected" title="Markdown Basics">Basics</a></li>
- <li><a href="/projects/markdown/syntax" title="Markdown Syntax Documentation">Syntax</a></li>
- <li><a href="/projects/markdown/license" title="Pricing and License Information">License</a></li>
- <li><a href="/projects/markdown/dingus" title="Online Markdown Web Form">Dingus</a></li>
-</ul>
-
-
-Getting the Gist of Markdown's Formatting Syntax
-------------------------------------------------
-
-This page offers a brief overview of what it's like to use Markdown.
-The [syntax page] [s] provides complete, detailed documentation for
-every feature, but Markdown should be very easy to pick up simply by
-looking at a few examples of it in action. The examples on this page
-are written in a before/after style, showing example syntax and the
-HTML output produced by Markdown.
-
-It's also helpful to simply try Markdown out; the [Dingus] [d] is a
-web application that allows you type your own Markdown-formatted text
-and translate it to XHTML.
-
-**Note:** This document is itself written using Markdown; you
-can [see the source for it by adding '.text' to the URL] [src].
-
- [s]: /projects/markdown/syntax "Markdown Syntax"
- [d]: /projects/markdown/dingus "Markdown Dingus"
- [src]: /projects/markdown/basics.text
-
-
-## Paragraphs, Headers, Blockquotes ##
-
-A paragraph is simply one or more consecutive lines of text, separated
-by one or more blank lines. (A blank line is any line that looks like a
-blank line -- a line containing nothing spaces or tabs is considered
-blank.) Normal paragraphs should not be indented with spaces or tabs.
-
-Markdown offers two styles of headers: *Setext* and *atx*.
-Setext-style headers for `<h1>` and `<h2>` are created by
-"underlining" with equal signs (`=`) and hyphens (`-`), respectively.
-To create an atx-style header, you put 1-6 hash marks (`#`) at the
-beginning of the line -- the number of hashes equals the resulting
-HTML header level.
-
-Blockquotes are indicated using email-style '`>`' angle brackets.
-
-Markdown:
-
- A First Level Header
- ====================
-
- A Second Level Header
- ---------------------
-
- Now is the time for all good men to come to
- the aid of their country. This is just a
- regular paragraph.
-
- The quick brown fox jumped over the lazy
- dog's back.
-
- ### Header 3
-
- > This is a blockquote.
- >
- > This is the second paragraph in the blockquote.
- >
- > ## This is an H2 in a blockquote
-
-
-Output:
-
- <h1>A First Level Header</h1>
-
- <h2>A Second Level Header</h2>
-
- <p>Now is the time for all good men to come to
- the aid of their country. This is just a
- regular paragraph.</p>
-
- <p>The quick brown fox jumped over the lazy
- dog's back.</p>
-
- <h3>Header 3</h3>
-
- <blockquote>
- <p>This is a blockquote.</p>
-
- <p>This is the second paragraph in the blockquote.</p>
-
- <h2>This is an H2 in a blockquote</h2>
- </blockquote>
-
-
-
-### Phrase Emphasis ###
-
-Markdown uses asterisks and underscores to indicate spans of emphasis.
-
-Markdown:
-
- Some of these words *are emphasized*.
- Some of these words _are emphasized also_.
-
- Use two asterisks for **strong emphasis**.
- Or, if you prefer, __use two underscores instead__.
-
-Output:
-
- <p>Some of these words <em>are emphasized</em>.
- Some of these words <em>are emphasized also</em>.</p>
-
- <p>Use two asterisks for <strong>strong emphasis</strong>.
- Or, if you prefer, <strong>use two underscores instead</strong>.</p>
-
-
-
-## Lists ##
-
-Unordered (bulleted) lists use asterisks, pluses, and hyphens (`*`,
-`+`, and `-`) as list markers. These three markers are
-interchangable; this:
-
- * Candy.
- * Gum.
- * Booze.
-
-this:
-
- + Candy.
- + Gum.
- + Booze.
-
-and this:
-
- - Candy.
- - Gum.
- - Booze.
-
-all produce the same output:
-
- <ul>
- <li>Candy.</li>
- <li>Gum.</li>
- <li>Booze.</li>
- </ul>
-
-Ordered (numbered) lists use regular numbers, followed by periods, as
-list markers:
-
- 1. Red
- 2. Green
- 3. Blue
-
-Output:
-
- <ol>
- <li>Red</li>
- <li>Green</li>
- <li>Blue</li>
- </ol>
-
-If you put blank lines between items, you'll get `<p>` tags for the
-list item text. You can create multi-paragraph list items by indenting
-the paragraphs by 4 spaces or 1 tab:
-
- * A list item.
-
- With multiple paragraphs.
-
- * Another item in the list.
-
-Output:
-
- <ul>
- <li><p>A list item.</p>
- <p>With multiple paragraphs.</p></li>
- <li><p>Another item in the list.</p></li>
- </ul>
-
-
-
-### Links ###
-
-Markdown supports two styles for creating links: *inline* and
-*reference*. With both styles, you use square brackets to delimit the
-text you want to turn into a link.
-
-Inline-style links use parentheses immediately after the link text.
-For example:
-
- This is an [example link](http://example.com/).
-
-Output:
-
- <p>This is an <a href="http://example.com/">
- example link</a>.</p>
-
-Optionally, you may include a title attribute in the parentheses:
-
- This is an [example link](http://example.com/ "With a Title").
-
-Output:
-
- <p>This is an <a href="http://example.com/" title="With a Title">
- example link</a>.</p>
-
-Reference-style links allow you to refer to your links by names, which
-you define elsewhere in your document:
-
- I get 10 times more traffic from [Google][1] than from
- [Yahoo][2] or [MSN][3].
-
- [1]: http://google.com/ "Google"
- [2]: http://search.yahoo.com/ "Yahoo Search"
- [3]: http://search.msn.com/ "MSN Search"
-
-Output:
-
- <p>I get 10 times more traffic from <a href="http://google.com/"
- title="Google">Google</a> than from <a href="http://search.yahoo.com/"
- title="Yahoo Search">Yahoo</a> or <a href="http://search.msn.com/"
- title="MSN Search">MSN</a>.</p>
-
-The title attribute is optional. Link names may contain letters,
-numbers and spaces, but are *not* case sensitive:
-
- I start my morning with a cup of coffee and
- [The New York Times][NY Times].
-
- [ny times]: http://www.nytimes.com/
-
-Output:
-
- <p>I start my morning with a cup of coffee and
- <a href="http://www.nytimes.com/">The New York Times</a>.</p>
-
-
-### Images ###
-
-Image syntax is very much like link syntax.
-
-Inline (titles are optional):
-
- 
-
-Reference-style:
-
- ![alt text][id]
-
- [id]: /path/to/img.jpg "Title"
-
-Both of the above examples produce the same output:
-
- <img src="/path/to/img.jpg" alt="alt text" title="Title" />
-
-
-
-### Code ###
-
-In a regular paragraph, you can create code span by wrapping text in
-backtick quotes. Any ampersands (`&`) and angle brackets (`<` or
-`>`) will automatically be translated into HTML entities. This makes
-it easy to use Markdown to write about HTML example code:
-
- I strongly recommend against using any `<blink>` tags.
-
- I wish SmartyPants used named entities like `—`
- instead of decimal-encoded entites like `—`.
-
-Output:
-
- <p>I strongly recommend against using any
- <code><blink></code> tags.</p>
-
- <p>I wish SmartyPants used named entities like
- <code>&mdash;</code> instead of decimal-encoded
- entites like <code>&#8212;</code>.</p>
-
-
-To specify an entire block of pre-formatted code, indent every line of
-the block by 4 spaces or 1 tab. Just like with code spans, `&`, `<`,
-and `>` characters will be escaped automatically.
-
-Markdown:
-
- If you want your page to validate under XHTML 1.0 Strict,
- you've got to put paragraph tags in your blockquotes:
-
- <blockquote>
- <p>For example.</p>
- </blockquote>
-
-Output:
-
- <p>If you want your page to validate under XHTML 1.0 Strict,
- you've got to put paragraph tags in your blockquotes:</p>
-
- <pre><code><blockquote>
- <p>For example.</p>
- </blockquote>
- </code></pre>
+++ /dev/null
-Markdown: Syntax
-================
-
-<ul id="ProjectSubmenu">
- <li><a href="/projects/markdown/" title="Markdown Project Page">Main</a></li>
- <li><a href="/projects/markdown/basics" title="Markdown Basics">Basics</a></li>
- <li><a class="selected" title="Markdown Syntax Documentation">Syntax</a></li>
- <li><a href="/projects/markdown/license" title="Pricing and License Information">License</a></li>
- <li><a href="/projects/markdown/dingus" title="Online Markdown Web Form">Dingus</a></li>
-</ul>
-
-
-* [Overview](#overview)
- * [Philosophy](#philosophy)
- * [Inline HTML](#html)
- * [Automatic Escaping for Special Characters](#autoescape)
-* [Block Elements](#block)
- * [Paragraphs and Line Breaks](#p)
- * [Headers](#header)
- * [Blockquotes](#blockquote)
- * [Lists](#list)
- * [Code Blocks](#precode)
- * [Horizontal Rules](#hr)
-* [Span Elements](#span)
- * [Links](#link)
- * [Emphasis](#em)
- * [Code](#code)
- * [Images](#img)
-* [Miscellaneous](#misc)
- * [Backslash Escapes](#backslash)
- * [Automatic Links](#autolink)
-
-
-**Note:** This document is itself written using Markdown; you
-can [see the source for it by adding '.text' to the URL][src].
-
- [src]: /projects/markdown/syntax.text
-
-* * *
-
-<h2 id="overview">Overview</h2>
-
-<h3 id="philosophy">Philosophy</h3>
-
-Markdown is intended to be as easy-to-read and easy-to-write as is feasible.
-
-Readability, however, is emphasized above all else. A Markdown-formatted
-document should be publishable as-is, as plain text, without looking
-like it's been marked up with tags or formatting instructions. While
-Markdown's syntax has been influenced by several existing text-to-HTML
-filters -- including [Setext] [1], [atx] [2], [Textile] [3], [reStructuredText] [4],
-[Grutatext] [5], and [EtText] [6] -- the single biggest source of
-inspiration for Markdown's syntax is the format of plain text email.
-
- [1]: http://docutils.sourceforge.net/mirror/setext.html
- [2]: http://www.aaronsw.com/2002/atx/
- [3]: http://textism.com/tools/textile/
- [4]: http://docutils.sourceforge.net/rst.html
- [5]: http://www.triptico.com/software/grutatxt.html
- [6]: http://ettext.taint.org/doc/
-
-To this end, Markdown's syntax is comprised entirely of punctuation
-characters, which punctuation characters have been carefully chosen so
-as to look like what they mean. E.g., asterisks around a word actually
-look like \*emphasis\*. Markdown lists look like, well, lists. Even
-blockquotes look like quoted passages of text, assuming you've ever
-used email.
-
-
-
-<h3 id="html">Inline HTML</h3>
-
-Markdown's syntax is intended for one purpose: to be used as a
-format for *writing* for the web.
-
-Markdown is not a replacement for HTML, or even close to it. Its
-syntax is very small, corresponding only to a very small subset of
-HTML tags. The idea is *not* to create a syntax that makes it easier
-to insert HTML tags. In my opinion, HTML tags are already easy to
-insert. The idea for Markdown is to make it easy to read, write, and
-edit prose. HTML is a *publishing* format; Markdown is a *writing*
-format. Thus, Markdown's formatting syntax only addresses issues that
-can be conveyed in plain text.
-
-For any markup that is not covered by Markdown's syntax, you simply
-use HTML itself. There's no need to preface it or delimit it to
-indicate that you're switching from Markdown to HTML; you just use
-the tags.
-
-The only restrictions are that block-level HTML elements -- e.g. `<div>`,
-`<table>`, `<pre>`, `<p>`, etc. -- must be separated from surrounding
-content by blank lines, and the start and end tags of the block should
-not be indented with tabs or spaces. Markdown is smart enough not
-to add extra (unwanted) `<p>` tags around HTML block-level tags.
-
-For example, to add an HTML table to a Markdown article:
-
- This is a regular paragraph.
-
- <table>
- <tr>
- <td>Foo</td>
- </tr>
- </table>
-
- This is another regular paragraph.
-
-Note that Markdown formatting syntax is not processed within block-level
-HTML tags. E.g., you can't use Markdown-style `*emphasis*` inside an
-HTML block.
-
-Span-level HTML tags -- e.g. `<span>`, `<cite>`, or `<del>` -- can be
-used anywhere in a Markdown paragraph, list item, or header. If you
-want, you can even use HTML tags instead of Markdown formatting; e.g. if
-you'd prefer to use HTML `<a>` or `<img>` tags instead of Markdown's
-link or image syntax, go right ahead.
-
-Unlike block-level HTML tags, Markdown syntax *is* processed within
-span-level tags.
-
-
-<h3 id="autoescape">Automatic Escaping for Special Characters</h3>
-
-In HTML, there are two characters that demand special treatment: `<`
-and `&`. Left angle brackets are used to start tags; ampersands are
-used to denote HTML entities. If you want to use them as literal
-characters, you must escape them as entities, e.g. `<`, and
-`&`.
-
-Ampersands in particular are bedeviling for web writers. If you want to
-write about 'AT&T', you need to write '`AT&T`'. You even need to
-escape ampersands within URLs. Thus, if you want to link to:
-
- http://images.google.com/images?num=30&q=larry+bird
-
-you need to encode the URL as:
-
- http://images.google.com/images?num=30&q=larry+bird
-
-in your anchor tag `href` attribute. Needless to say, this is easy to
-forget, and is probably the single most common source of HTML validation
-errors in otherwise well-marked-up web sites.
-
-Markdown allows you to use these characters naturally, taking care of
-all the necessary escaping for you. If you use an ampersand as part of
-an HTML entity, it remains unchanged; otherwise it will be translated
-into `&`.
-
-So, if you want to include a copyright symbol in your article, you can write:
-
- ©
-
-and Markdown will leave it alone. But if you write:
-
- AT&T
-
-Markdown will translate it to:
-
- AT&T
-
-Similarly, because Markdown supports [inline HTML](#html), if you use
-angle brackets as delimiters for HTML tags, Markdown will treat them as
-such. But if you write:
-
- 4 < 5
-
-Markdown will translate it to:
-
- 4 < 5
-
-However, inside Markdown code spans and blocks, angle brackets and
-ampersands are *always* encoded automatically. This makes it easy to use
-Markdown to write about HTML code. (As opposed to raw HTML, which is a
-terrible format for writing about HTML syntax, because every single `<`
-and `&` in your example code needs to be escaped.)
-
-
-* * *
-
-
-<h2 id="block">Block Elements</h2>
-
-
-<h3 id="p">Paragraphs and Line Breaks</h3>
-
-A paragraph is simply one or more consecutive lines of text, separated
-by one or more blank lines. (A blank line is any line that looks like a
-blank line -- a line containing nothing but spaces or tabs is considered
-blank.) Normal paragraphs should not be indented with spaces or tabs.
-
-The implication of the "one or more consecutive lines of text" rule is
-that Markdown supports "hard-wrapped" text paragraphs. This differs
-significantly from most other text-to-HTML formatters (including Movable
-Type's "Convert Line Breaks" option) which translate every line break
-character in a paragraph into a `<br />` tag.
-
-When you *do* want to insert a `<br />` break tag using Markdown, you
-end a line with two or more spaces, then type return.
-
-Yes, this takes a tad more effort to create a `<br />`, but a simplistic
-"every line break is a `<br />`" rule wouldn't work for Markdown.
-Markdown's email-style [blockquoting][bq] and multi-paragraph [list items][l]
-work best -- and look better -- when you format them with hard breaks.
-
- [bq]: #blockquote
- [l]: #list
-
-
-
-<h3 id="header">Headers</h3>
-
-Markdown supports two styles of headers, [Setext] [1] and [atx] [2].
-
-Setext-style headers are "underlined" using equal signs (for first-level
-headers) and dashes (for second-level headers). For example:
-
- This is an H1
- =============
-
- This is an H2
- -------------
-
-Any number of underlining `=`'s or `-`'s will work.
-
-Atx-style headers use 1-6 hash characters at the start of the line,
-corresponding to header levels 1-6. For example:
-
- # This is an H1
-
- ## This is an H2
-
- ###### This is an H6
-
-Optionally, you may "close" atx-style headers. This is purely
-cosmetic -- you can use this if you think it looks better. The
-closing hashes don't even need to match the number of hashes
-used to open the header. (The number of opening hashes
-determines the header level.) :
-
- # This is an H1 #
-
- ## This is an H2 ##
-
- ### This is an H3 ######
-
-
-<h3 id="blockquote">Blockquotes</h3>
-
-Markdown uses email-style `>` characters for blockquoting. If you're
-familiar with quoting passages of text in an email message, then you
-know how to create a blockquote in Markdown. It looks best if you hard
-wrap the text and put a `>` before every line:
-
- > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
- > consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
- > Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
- >
- > Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
- > id sem consectetuer libero luctus adipiscing.
-
-Markdown allows you to be lazy and only put the `>` before the first
-line of a hard-wrapped paragraph:
-
- > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
- consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
- Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
-
- > Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
- id sem consectetuer libero luctus adipiscing.
-
-Blockquotes can be nested (i.e. a blockquote-in-a-blockquote) by
-adding additional levels of `>`:
-
- > This is the first level of quoting.
- >
- > > This is nested blockquote.
- >
- > Back to the first level.
-
-Blockquotes can contain other Markdown elements, including headers, lists,
-and code blocks:
-
- > ## This is a header.
- >
- > 1. This is the first list item.
- > 2. This is the second list item.
- >
- > Here's some example code:
- >
- > return shell_exec("echo $input | $markdown_script");
-
-Any decent text editor should make email-style quoting easy. For
-example, with BBEdit, you can make a selection and choose Increase
-Quote Level from the Text menu.
-
-
-<h3 id="list">Lists</h3>
-
-Markdown supports ordered (numbered) and unordered (bulleted) lists.
-
-Unordered lists use asterisks, pluses, and hyphens -- interchangably
--- as list markers:
-
- * Red
- * Green
- * Blue
-
-is equivalent to:
-
- + Red
- + Green
- + Blue
-
-and:
-
- - Red
- - Green
- - Blue
-
-Ordered lists use numbers followed by periods:
-
- 1. Bird
- 2. McHale
- 3. Parish
-
-It's important to note that the actual numbers you use to mark the
-list have no effect on the HTML output Markdown produces. The HTML
-Markdown produces from the above list is:
-
- <ol>
- <li>Bird</li>
- <li>McHale</li>
- <li>Parish</li>
- </ol>
-
-If you instead wrote the list in Markdown like this:
-
- 1. Bird
- 1. McHale
- 1. Parish
-
-or even:
-
- 3. Bird
- 1. McHale
- 8. Parish
-
-you'd get the exact same HTML output. The point is, if you want to,
-you can use ordinal numbers in your ordered Markdown lists, so that
-the numbers in your source match the numbers in your published HTML.
-But if you want to be lazy, you don't have to.
-
-If you do use lazy list numbering, however, you should still start the
-list with the number 1. At some point in the future, Markdown may support
-starting ordered lists at an arbitrary number.
-
-List markers typically start at the left margin, but may be indented by
-up to three spaces. List markers must be followed by one or more spaces
-or a tab.
-
-To make lists look nice, you can wrap items with hanging indents:
-
- * Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
- Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
- viverra nec, fringilla in, laoreet vitae, risus.
- * Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
- Suspendisse id sem consectetuer libero luctus adipiscing.
-
-But if you want to be lazy, you don't have to:
-
- * Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
- Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
- viverra nec, fringilla in, laoreet vitae, risus.
- * Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
- Suspendisse id sem consectetuer libero luctus adipiscing.
-
-If list items are separated by blank lines, Markdown will wrap the
-items in `<p>` tags in the HTML output. For example, this input:
-
- * Bird
- * Magic
-
-will turn into:
-
- <ul>
- <li>Bird</li>
- <li>Magic</li>
- </ul>
-
-But this:
-
- * Bird
-
- * Magic
-
-will turn into:
-
- <ul>
- <li><p>Bird</p></li>
- <li><p>Magic</p></li>
- </ul>
-
-List items may consist of multiple paragraphs. Each subsequent
-paragraph in a list item must be indented by either 4 spaces
-or one tab:
-
- 1. This is a list item with two paragraphs. Lorem ipsum dolor
- sit amet, consectetuer adipiscing elit. Aliquam hendrerit
- mi posuere lectus.
-
- Vestibulum enim wisi, viverra nec, fringilla in, laoreet
- vitae, risus. Donec sit amet nisl. Aliquam semper ipsum
- sit amet velit.
-
- 2. Suspendisse id sem consectetuer libero luctus adipiscing.
-
-It looks nice if you indent every line of the subsequent
-paragraphs, but here again, Markdown will allow you to be
-lazy:
-
- * This is a list item with two paragraphs.
-
- This is the second paragraph in the list item. You're
- only required to indent the first line. Lorem ipsum dolor
- sit amet, consectetuer adipiscing elit.
-
- * Another item in the same list.
-
-To put a blockquote within a list item, the blockquote's `>`
-delimiters need to be indented:
-
- * A list item with a blockquote:
-
- > This is a blockquote
- > inside a list item.
-
-To put a code block within a list item, the code block needs
-to be indented *twice* -- 8 spaces or two tabs:
-
- * A list item with a code block:
-
- <code goes here>
-
-
-It's worth noting that it's possible to trigger an ordered list by
-accident, by writing something like this:
-
- 1986. What a great season.
-
-In other words, a *number-period-space* sequence at the beginning of a
-line. To avoid this, you can backslash-escape the period:
-
- 1986\. What a great season.
-
-
-
-<h3 id="precode">Code Blocks</h3>
-
-Pre-formatted code blocks are used for writing about programming or
-markup source code. Rather than forming normal paragraphs, the lines
-of a code block are interpreted literally. Markdown wraps a code block
-in both `<pre>` and `<code>` tags.
-
-To produce a code block in Markdown, simply indent every line of the
-block by at least 4 spaces or 1 tab. For example, given this input:
-
- This is a normal paragraph:
-
- This is a code block.
-
-Markdown will generate:
-
- <p>This is a normal paragraph:</p>
-
- <pre><code>This is a code block.
- </code></pre>
-
-One level of indentation -- 4 spaces or 1 tab -- is removed from each
-line of the code block. For example, this:
-
- Here is an example of AppleScript:
-
- tell application "Foo"
- beep
- end tell
-
-will turn into:
-
- <p>Here is an example of AppleScript:</p>
-
- <pre><code>tell application "Foo"
- beep
- end tell
- </code></pre>
-
-A code block continues until it reaches a line that is not indented
-(or the end of the article).
-
-Within a code block, ampersands (`&`) and angle brackets (`<` and `>`)
-are automatically converted into HTML entities. This makes it very
-easy to include example HTML source code using Markdown -- just paste
-it and indent it, and Markdown will handle the hassle of encoding the
-ampersands and angle brackets. For example, this:
-
- <div class="footer">
- © 2004 Foo Corporation
- </div>
-
-will turn into:
-
- <pre><code><div class="footer">
- &copy; 2004 Foo Corporation
- </div>
- </code></pre>
-
-Regular Markdown syntax is not processed within code blocks. E.g.,
-asterisks are just literal asterisks within a code block. This means
-it's also easy to use Markdown to write about Markdown's own syntax.
-
-
-
-<h3 id="hr">Horizontal Rules</h3>
-
-You can produce a horizontal rule tag (`<hr />`) by placing three or
-more hyphens, asterisks, or underscores on a line by themselves. If you
-wish, you may use spaces between the hyphens or asterisks. Each of the
-following lines will produce a horizontal rule:
-
- * * *
-
- ***
-
- *****
-
- - - -
-
- ---------------------------------------
-
- _ _ _
-
-
-* * *
-
-<h2 id="span">Span Elements</h2>
-
-<h3 id="link">Links</h3>
-
-Markdown supports two style of links: *inline* and *reference*.
-
-In both styles, the link text is delimited by [square brackets].
-
-To create an inline link, use a set of regular parentheses immediately
-after the link text's closing square bracket. Inside the parentheses,
-put the URL where you want the link to point, along with an *optional*
-title for the link, surrounded in quotes. For example:
-
- This is [an example](http://example.com/ "Title") inline link.
-
- [This link](http://example.net/) has no title attribute.
-
-Will produce:
-
- <p>This is <a href="http://example.com/" title="Title">
- an example</a> inline link.</p>
-
- <p><a href="http://example.net/">This link</a> has no
- title attribute.</p>
-
-If you're referring to a local resource on the same server, you can
-use relative paths:
-
- See my [About](/about/) page for details.
-
-Reference-style links use a second set of square brackets, inside
-which you place a label of your choosing to identify the link:
-
- This is [an example][id] reference-style link.
-
-You can optionally use a space to separate the sets of brackets:
-
- This is [an example] [id] reference-style link.
-
-Then, anywhere in the document, you define your link label like this,
-on a line by itself:
-
- [id]: http://example.com/ "Optional Title Here"
-
-That is:
-
-* Square brackets containing the link identifier (optionally
- indented from the left margin using up to three spaces);
-* followed by a colon;
-* followed by one or more spaces (or tabs);
-* followed by the URL for the link;
-* optionally followed by a title attribute for the link, enclosed
- in double or single quotes.
-
-The link URL may, optionally, be surrounded by angle brackets:
-
- [id]: <http://example.com/> "Optional Title Here"
-
-You can put the title attribute on the next line and use extra spaces
-or tabs for padding, which tends to look better with longer URLs:
-
- [id]: http://example.com/longish/path/to/resource/here
- "Optional Title Here"
-
-Link definitions are only used for creating links during Markdown
-processing, and are stripped from your document in the HTML output.
-
-Link definition names may constist of letters, numbers, spaces, and punctuation -- but they are *not* case sensitive. E.g. these two links:
-
- [link text][a]
- [link text][A]
-
-are equivalent.
-
-The *implicit link name* shortcut allows you to omit the name of the
-link, in which case the link text itself is used as the name.
-Just use an empty set of square brackets -- e.g., to link the word
-"Google" to the google.com web site, you could simply write:
-
- [Google][]
-
-And then define the link:
-
- [Google]: http://google.com/
-
-Because link names may contain spaces, this shortcut even works for
-multiple words in the link text:
-
- Visit [Daring Fireball][] for more information.
-
-And then define the link:
-
- [Daring Fireball]: http://daringfireball.net/
-
-Link definitions can be placed anywhere in your Markdown document. I
-tend to put them immediately after each paragraph in which they're
-used, but if you want, you can put them all at the end of your
-document, sort of like footnotes.
-
-Here's an example of reference links in action:
-
- I get 10 times more traffic from [Google] [1] than from
- [Yahoo] [2] or [MSN] [3].
-
- [1]: http://google.com/ "Google"
- [2]: http://search.yahoo.com/ "Yahoo Search"
- [3]: http://search.msn.com/ "MSN Search"
-
-Using the implicit link name shortcut, you could instead write:
-
- I get 10 times more traffic from [Google][] than from
- [Yahoo][] or [MSN][].
-
- [google]: http://google.com/ "Google"
- [yahoo]: http://search.yahoo.com/ "Yahoo Search"
- [msn]: http://search.msn.com/ "MSN Search"
-
-Both of the above examples will produce the following HTML output:
-
- <p>I get 10 times more traffic from <a href="http://google.com/"
- title="Google">Google</a> than from
- <a href="http://search.yahoo.com/" title="Yahoo Search">Yahoo</a>
- or <a href="http://search.msn.com/" title="MSN Search">MSN</a>.</p>
-
-For comparison, here is the same paragraph written using
-Markdown's inline link style:
-
- I get 10 times more traffic from [Google](http://google.com/ "Google")
- than from [Yahoo](http://search.yahoo.com/ "Yahoo Search") or
- [MSN](http://search.msn.com/ "MSN Search").
-
-The point of reference-style links is not that they're easier to
-write. The point is that with reference-style links, your document
-source is vastly more readable. Compare the above examples: using
-reference-style links, the paragraph itself is only 81 characters
-long; with inline-style links, it's 176 characters; and as raw HTML,
-it's 234 characters. In the raw HTML, there's more markup than there
-is text.
-
-With Markdown's reference-style links, a source document much more
-closely resembles the final output, as rendered in a browser. By
-allowing you to move the markup-related metadata out of the paragraph,
-you can add links without interrupting the narrative flow of your
-prose.
-
-
-<h3 id="em">Emphasis</h3>
-
-Markdown treats asterisks (`*`) and underscores (`_`) as indicators of
-emphasis. Text wrapped with one `*` or `_` will be wrapped with an
-HTML `<em>` tag; double `*`'s or `_`'s will be wrapped with an HTML
-`<strong>` tag. E.g., this input:
-
- *single asterisks*
-
- _single underscores_
-
- **double asterisks**
-
- __double underscores__
-
-will produce:
-
- <em>single asterisks</em>
-
- <em>single underscores</em>
-
- <strong>double asterisks</strong>
-
- <strong>double underscores</strong>
-
-You can use whichever style you prefer; the lone restriction is that
-the same character must be used to open and close an emphasis span.
-
-Emphasis can be used in the middle of a word:
-
- un*fucking*believable
-
-But if you surround an `*` or `_` with spaces, it'll be treated as a
-literal asterisk or underscore.
-
-To produce a literal asterisk or underscore at a position where it
-would otherwise be used as an emphasis delimiter, you can backslash
-escape it:
-
- \*this text is surrounded by literal asterisks\*
-
-
-
-<h3 id="code">Code</h3>
-
-To indicate a span of code, wrap it with backtick quotes (`` ` ``).
-Unlike a pre-formatted code block, a code span indicates code within a
-normal paragraph. For example:
-
- Use the `printf()` function.
-
-will produce:
-
- <p>Use the <code>printf()</code> function.</p>
-
-To include a literal backtick character within a code span, you can use
-multiple backticks as the opening and closing delimiters:
-
- ``There is a literal backtick (`) here.``
-
-which will produce this:
-
- <p><code>There is a literal backtick (`) here.</code></p>
-
-The backtick delimiters surrounding a code span may include spaces --
-one after the opening, one before the closing. This allows you to place
-literal backtick characters at the beginning or end of a code span:
-
- A single backtick in a code span: `` ` ``
-
- A backtick-delimited string in a code span: `` `foo` ``
-
-will produce:
-
- <p>A single backtick in a code span: <code>`</code></p>
-
- <p>A backtick-delimited string in a code span: <code>`foo`</code></p>
-
-With a code span, ampersands and angle brackets are encoded as HTML
-entities automatically, which makes it easy to include example HTML
-tags. Markdown will turn this:
-
- Please don't use any `<blink>` tags.
-
-into:
-
- <p>Please don't use any <code><blink></code> tags.</p>
-
-You can write this:
-
- `—` is the decimal-encoded equivalent of `—`.
-
-to produce:
-
- <p><code>&#8212;</code> is the decimal-encoded
- equivalent of <code>&mdash;</code>.</p>
-
-
-
-<h3 id="img">Images</h3>
-
-Admittedly, it's fairly difficult to devise a "natural" syntax for
-placing images into a plain text document format.
-
-Markdown uses an image syntax that is intended to resemble the syntax
-for links, allowing for two styles: *inline* and *reference*.
-
-Inline image syntax looks like this:
-
- 
-
- 
-
-That is:
-
-* An exclamation mark: `!`;
-* followed by a set of square brackets, containing the `alt`
- attribute text for the image;
-* followed by a set of parentheses, containing the URL or path to
- the image, and an optional `title` attribute enclosed in double
- or single quotes.
-
-Reference-style image syntax looks like this:
-
- ![Alt text][id]
-
-Where "id" is the name of a defined image reference. Image references
-are defined using syntax identical to link references:
-
- [id]: url/to/image "Optional title attribute"
-
-As of this writing, Markdown has no syntax for specifying the
-dimensions of an image; if this is important to you, you can simply
-use regular HTML `<img>` tags.
-
-
-* * *
-
-
-<h2 id="misc">Miscellaneous</h2>
-
-<h3 id="autolink">Automatic Links</h3>
-
-Markdown supports a shortcut style for creating "automatic" links for URLs and email addresses: simply surround the URL or email address with angle brackets. What this means is that if you want to show the actual text of a URL or email address, and also have it be a clickable link, you can do this:
-
- <http://example.com/>
-
-Markdown will turn this into:
-
- <a href="http://example.com/">http://example.com/</a>
-
-Automatic links for email addresses work similarly, except that
-Markdown will also perform a bit of randomized decimal and hex
-entity-encoding to help obscure your address from address-harvesting
-spambots. For example, Markdown will turn this:
-
- <address@example.com>
-
-into something like this:
-
- <a href="mailto:addre
- ss@example.co
- m">address@exa
- mple.com</a>
-
-which will render in a browser as a clickable link to "address@example.com".
-
-(This sort of entity-encoding trick will indeed fool many, if not
-most, address-harvesting bots, but it definitely won't fool all of
-them. It's better than nothing, but an address published in this way
-will probably eventually start receiving spam.)
-
-
-
-<h3 id="backslash">Backslash Escapes</h3>
-
-Markdown allows you to use backslash escapes to generate literal
-characters which would otherwise have special meaning in Markdown's
-formatting syntax. For example, if you wanted to surround a word with
-literal asterisks (instead of an HTML `<em>` tag), you can backslashes
-before the asterisks, like this:
-
- \*literal asterisks\*
-
-Markdown provides backslash escapes for the following characters:
-
- \ backslash
- ` backtick
- * asterisk
- _ underscore
- {} curly braces
- [] square brackets
- () parentheses
- # hash mark
- + plus sign
- - minus sign (hyphen)
- . dot
- ! exclamation mark
-
+++ /dev/null
-> foo
->
-> > bar
->
-> foo
+++ /dev/null
-## Unordered
-
-Asterisks tight:
-
-* asterisk 1
-* asterisk 2
-* asterisk 3
-
-
-Asterisks loose:
-
-* asterisk 1
-
-* asterisk 2
-
-* asterisk 3
-
-* * *
-
-Pluses tight:
-
-+ Plus 1
-+ Plus 2
-+ Plus 3
-
-
-Pluses loose:
-
-+ Plus 1
-
-+ Plus 2
-
-+ Plus 3
-
-* * *
-
-
-Minuses tight:
-
-- Minus 1
-- Minus 2
-- Minus 3
-
-
-Minuses loose:
-
-- Minus 1
-
-- Minus 2
-
-- Minus 3
-
-
-## Ordered
-
-Tight:
-
-1. First
-2. Second
-3. Third
-
-and:
-
-1. One
-2. Two
-3. Three
-
-
-Loose using tabs:
-
-1. First
-
-2. Second
-
-3. Third
-
-and using spaces:
-
-1. One
-
-2. Two
-
-3. Three
-
-Multiple paragraphs:
-
-1. Item 1, graf one.
-
- Item 2. graf two. The quick brown fox jumped over the lazy dog's
- back.
-
-2. Item 2.
-
-3. Item 3.
-
-
-
-## Nested
-
-* Tab
- * Tab
- * Tab
-
-Here's another:
-
-1. First
-2. Second:
- * Fee
- * Fie
- * Foe
-3. Third
-
-Same thing but with paragraphs:
-
-1. First
-
-2. Second:
- * Fee
- * Fie
- * Foe
-
-3. Third
+++ /dev/null
-***This is strong and em.***
-
-So is ***this*** word.
-
-___This is strong and em.___
-
-So is ___this___ word.
+++ /dev/null
-+ this is a list item
- indented with tabs
-
-+ this is a list item
- indented with spaces
-
-Code:
-
- this code block is indented by one tab
-
-And:
-
- this code block is indented by two tabs
-
-And:
-
- + this is an example list item
- indented with tabs
-
- + this is an example list item
- indented with spaces
+++ /dev/null
-> A list within a blockquote:
->
-> * asterisk 1
-> * asterisk 2
-> * asterisk 3
+++ /dev/null
-
-Lorem ipsum {@id=lorem}
-=================================
-
-Dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
-incididunt ut labore et dolore magna aliqua.
-
-* Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
- nisi ut aliquip ex ea commodo consequat.{@class=first_item}
-
-* Duis aute irure dolor in reprehenderit in voluptate velit esse
- cillum dolore eu fugiat nulla pariatur2. Excepteur sint occaecat
- cupidatat non proident, sunt in culpa qui officia deserunt mollit
- anim id est laborum.
-
-Duis aute **irure{@type=term}** dolor in reprehenderit in voluptate
-velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
-occaecat cupidatat non proident, sunt in culpa qui officia deserunt
-mollit anim id est laborum.
+++ /dev/null
-Lorem ipsum <yuri@domain.org>, etc.
-
-* An email address in a list
-* <yuri@domain.org>
-* Another item.
-
-
+++ /dev/null
-Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
-tempor incididunt ut labore et dolore magna aliqua[^2]. Ut enim ad minim
-veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
-commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
-velit esse cillum dolore eu fugiat nulla pariatur[^1]. Excepteur sint
-occaecat cupidatat non proident, sunt in culpa qui officia deserunt
-mollit anim id est laborum.
-
-[^1]: Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit
- aut fugit, sed quia consequuntur magni dolores eos qui ratione
- voluptatem sequi nesciunt.
-
- Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet,
- consectetur, adipisci velit, sed quia non numquam eius modi
- tempora incidunt ut labore et dolore magnam aliquam quaerat
- voluptatem.
-
-[^2]: Sed ut perspiciatis unde omnis iste natus error sit voluptatem
- accusantium doloremque laudantium, totam rem aperiam, eaque ipsa
- quae ab illo inventore veritatis et quasi architecto beatae vitae
- dicta sunt explicabo.
-
-* Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
- eiusmod tempor incididunt ut labore et dolore[^foo] magna aliqua.
-
-[^foo]: Ut enim ad minim veniam, quis nostrud exercitation ullamco
- laboris nisi ut aliquip ex ea commodo consequat.
-
-Duis aute irure dolor in reprehenderit in voluptate
-velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
-occaecat cupidatat non proident, sunt in culpa qui officia deserunt
-mollit anim id est laborum.
+++ /dev/null
-## A plain header
-
-Let's first have a plain header
-
-An underlined header
-====================
-
-(That's also useful)
-
-# A header with a [link](http://www.link.com)
-
-First with a hash
-
-Another with a [link][a]
-------------------------
-This time underlined
-
-[a]: http://www.link.com/
+++ /dev/null
-AT&T has an ampersand in their name.
-
-AT&T is another way to write it.
-
-This & that.
-
-4 < 5.
-
-6 > 5.
-
-Here's a [link] [1] with an ampersand in the URL.
-
-Here's a link with an amersand in the link text: [AT&T] [2].
-
-Here's an inline [link](/script?foo=1&bar=2).
-
-Here's an inline [link](</script?foo=1&bar=2>).
-
-
-[1]: http://example.com/?foo=1&bar=2
-[2]: http://att.com/ "AT&T"
\ No newline at end of file
+++ /dev/null
-Link: <http://example.com/>.
-
-With an ampersand: <http://example.com/?foo=1&bar=2>
-
-* In a list?
-* <http://example.com/>
-* It should.
-
-> Blockquoted: <http://example.com/>
-
-Auto-links should not occur here: `<http://example.com/>`
-
- or here: <http://example.com/>
\ No newline at end of file
+++ /dev/null
-These should all get escaped:
-
-Backslash: \\
-
-Backtick: \`
-
-Asterisk: \*
-
-Underscore: \_
-
-Left brace: \{
-
-Right brace: \}
-
-Left bracket: \[
-
-Right bracket: \]
-
-Left paren: \(
-
-Right paren: \)
-
-Greater-than: \>
-
-Hash: \#
-
-Period: \.
-
-Bang: \!
-
-Plus: \+
-
-Minus: \-
-
-
-
-These should not, because they occur within a code block:
-
- Backslash: \\
-
- Backtick: \`
-
- Asterisk: \*
-
- Underscore: \_
-
- Left brace: \{
-
- Right brace: \}
-
- Left bracket: \[
-
- Right bracket: \]
-
- Left paren: \(
-
- Right paren: \)
-
- Greater-than: \>
-
- Hash: \#
-
- Period: \.
-
- Bang: \!
-
- Plus: \+
-
- Minus: \-
-
-
-Nor should these, which occur in code spans:
-
-Backslash: `\\`
-
-Backtick: `` \` ``
-
-Asterisk: `\*`
-
-Underscore: `\_`
-
-Left brace: `\{`
-
-Right brace: `\}`
-
-Left bracket: `\[`
-
-Right bracket: `\]`
-
-Left paren: `\(`
-
-Right paren: `\)`
-
-Greater-than: `\>`
-
-Hash: `\#`
-
-Period: `\.`
-
-Bang: `\!`
-
-Plus: `\+`
-
-Minus: `\-`
-
-
-These should get escaped, even though they're matching pairs for
-other Markdown constructs:
-
-\*asterisks\*
-
-\_underscores\_
-
-\`backticks\`
-
-This is a code span with a literal backslash-backtick sequence: `` \` ``
-
-This is a tag with unescaped backticks <span attr='`ticks`'>bar</span>.
-
-This is a tag with backslashes <span attr='\\backslashes\\'>bar</span>.
+++ /dev/null
-> Example:
->
-> sub status {
-> print "working";
-> }
->
-> Or:
->
-> sub status {
-> return "working";
-> }
+++ /dev/null
- code block on the first line
-
-Regular text.
-
- code block indented by spaces
-
-Regular text.
-
- the lines in this block
- all contain trailing spaces
-
-Regular Text.
-
- code block on the last line
\ No newline at end of file
+++ /dev/null
-`<test a="` content of attribute `">`
-
-Fix for backticks within HTML tag: <span attr='`ticks`'>like this</span>
-
-Here's how you put `` `backticks` `` in a code span.
\ No newline at end of file
+++ /dev/null
-In Markdown 1.0.0 and earlier. Version
-8. This line turns into a list item.
-Because a hard-wrapped line in the
-middle of a paragraph looked like a
-list item.
-
-Here's one with a bullet.
-* criminey.
+++ /dev/null
-Dashes:
-
----
-
- ---
-
- ---
-
- ---
-
- ---
-
-- - -
-
- - - -
-
- - - -
-
- - - -
-
- - - -
-
-
-Asterisks:
-
-***
-
- ***
-
- ***
-
- ***
-
- ***
-
-* * *
-
- * * *
-
- * * *
-
- * * *
-
- * * *
-
-
-Underscores:
-
-___
-
- ___
-
- ___
-
- ___
-
- ___
-
-_ _ _
-
- _ _ _
-
- _ _ _
-
- _ _ _
-
- _ _ _
+++ /dev/null
-
-
-
-
-Inline within a paragraph: [alt text](/url/).
-
-
-
-
-
-
-
-.
-
-![Empty]()
-
-.jpg)
-
-
-![alt text][foo]
-
- [foo]: /url/
-
-![alt text][bar]
-
- [bar]: /url/ "Title here"
\ No newline at end of file
+++ /dev/null
-Simple block on one line:
-
-<div>foo</div>
-
-And nested without indentation:
-
-<div>
-<div>
-<div>
-foo
-</div>
-<div style=">"/>
-</div>
-<div>bar</div>
-</div>
-
-And with attributes:
-
-<div>
- <div id="foo">
- </div>
-</div>
-
-This was broken in 1.0.2b7:
-
-<div class="inlinepage">
-<div class="toggleableend">
-foo
-</div>
-</div>
+++ /dev/null
-Here's a simple block:
-
-<div>
- foo
-</div>
-
-This should be a code block, though:
-
- <div>
- foo
- </div>
-
-As should this:
-
- <div>foo</div>
-
-Now, nested:
-
-<div>
- <div>
- <div>
- foo
- </div>
- </div>
-</div>
-
-This should just be an HTML comment:
-
-<!-- Comment -->
-
-Multiline:
-
-<!--
-Blah
-Blah
--->
-
-Code block:
-
- <!-- Comment -->
-
-Just plain comment, with trailing spaces on the line:
-
-<!-- foo -->
-
-Code:
-
- <hr />
-
-Hr's:
-
-<hr>
-
-<hr/>
-
-<hr />
-
-<hr>
-
-<hr/>
-
-<hr />
-
-<hr class="foo" id="bar" />
-
-<hr class="foo" id="bar"/>
-
-<hr class="foo" id="bar" >
-
+++ /dev/null
-Paragraph one.
-
-<!-- This is a simple comment -->
-
-<!--
- This is another comment.
--->
-
-Paragraph two.
-
-<!-- one comment block -- -- with two comments -->
-
-The end.
+++ /dev/null
-Just a [URL](/url/).
-
-[URL and title](/url/ "title").
-
-[URL and title](/url/ "title preceded by two spaces").
-
-[URL and title](/url/ "title preceded by a tab").
-
-[URL and title](/url/ "title has spaces afterward" ).
-
-[URL wrapped in angle brackets](</url/>).
-
-[URL w/ angle brackets + title](</url/> "Here's the title").
-
-[Empty]().
-
-[With parens in the URL](http://en.wikipedia.org/wiki/WIMP_(computing))
-
-(With outer parens and [parens in url](/foo(bar)))
-
-
-[With parens in the URL](/foo(bar) "and a title")
-
-(With outer parens and [parens in url](/foo(bar) "and a title"))
+++ /dev/null
-Foo [bar] [1].
-
-Foo [bar][1].
-
-Foo [bar]
-[1].
-
-[1]: /url/ "Title"
-
-
-With [embedded [brackets]] [b].
-
-
-Indented [once][].
-
-Indented [twice][].
-
-Indented [thrice][].
-
-Indented [four][] times.
-
- [once]: /url
-
- [twice]: /url
-
- [thrice]: /url
-
- [four]: /url
-
-
-[b]: /url/
-
-* * *
-
-[this] [this] should work
-
-So should [this][this].
-
-And [this] [].
-
-And [this][].
-
-And [this].
-
-But not [that] [].
-
-Nor [that][].
-
-Nor [that].
-
-[Something in brackets like [this][] should work]
-
-[Same with [this].]
-
-In this case, [this](/somethingelse/) points to something else.
-
-Backslashing should suppress \[this] and [this\].
-
-[this]: foo
-
-
-* * *
-
-Here's one where the [link
-breaks] across lines.
-
-Here's another where the [link
-breaks] across lines, but with a line-ending space.
-
-
-[link breaks]: /url/
+++ /dev/null
-This is the [simple case].
-
-[simple case]: /simple
-
-
-
-This one has a [line
-break].
-
-This one has a [line
-break] with a line-ending space.
-
-[line break]: /foo
-
-
-[this] [that] and the [other]
-
-[this]: /this
-[that]: /that
-[other]: /other
+++ /dev/null
-Foo [bar][].
-
-Foo [bar](/url/ "Title with "quotes" inside").
-
-
- [bar]: /url/ "Title with "quotes" inside"
-
+++ /dev/null
-Markdown: Basics
-================
-
-<ul id="ProjectSubmenu">
- <li><a href="/projects/markdown/" title="Markdown Project Page">Main</a></li>
- <li><a class="selected" title="Markdown Basics">Basics</a></li>
- <li><a href="/projects/markdown/syntax" title="Markdown Syntax Documentation">Syntax</a></li>
- <li><a href="/projects/markdown/license" title="Pricing and License Information">License</a></li>
- <li><a href="/projects/markdown/dingus" title="Online Markdown Web Form">Dingus</a></li>
-</ul>
-
-
-Getting the Gist of Markdown's Formatting Syntax
-------------------------------------------------
-
-This page offers a brief overview of what it's like to use Markdown.
-The [syntax page] [s] provides complete, detailed documentation for
-every feature, but Markdown should be very easy to pick up simply by
-looking at a few examples of it in action. The examples on this page
-are written in a before/after style, showing example syntax and the
-HTML output produced by Markdown.
-
-It's also helpful to simply try Markdown out; the [Dingus] [d] is a
-web application that allows you type your own Markdown-formatted text
-and translate it to XHTML.
-
-**Note:** This document is itself written using Markdown; you
-can [see the source for it by adding '.text' to the URL] [src].
-
- [s]: /projects/markdown/syntax "Markdown Syntax"
- [d]: /projects/markdown/dingus "Markdown Dingus"
- [src]: /projects/markdown/basics.text
-
-
-## Paragraphs, Headers, Blockquotes ##
-
-A paragraph is simply one or more consecutive lines of text, separated
-by one or more blank lines. (A blank line is any line that looks like a
-blank line -- a line containing nothing spaces or tabs is considered
-blank.) Normal paragraphs should not be indented with spaces or tabs.
-
-Markdown offers two styles of headers: *Setext* and *atx*.
-Setext-style headers for `<h1>` and `<h2>` are created by
-"underlining" with equal signs (`=`) and hyphens (`-`), respectively.
-To create an atx-style header, you put 1-6 hash marks (`#`) at the
-beginning of the line -- the number of hashes equals the resulting
-HTML header level.
-
-Blockquotes are indicated using email-style '`>`' angle brackets.
-
-Markdown:
-
- A First Level Header
- ====================
-
- A Second Level Header
- ---------------------
-
- Now is the time for all good men to come to
- the aid of their country. This is just a
- regular paragraph.
-
- The quick brown fox jumped over the lazy
- dog's back.
-
- ### Header 3
-
- > This is a blockquote.
- >
- > This is the second paragraph in the blockquote.
- >
- > ## This is an H2 in a blockquote
-
-
-Output:
-
- <h1>A First Level Header</h1>
-
- <h2>A Second Level Header</h2>
-
- <p>Now is the time for all good men to come to
- the aid of their country. This is just a
- regular paragraph.</p>
-
- <p>The quick brown fox jumped over the lazy
- dog's back.</p>
-
- <h3>Header 3</h3>
-
- <blockquote>
- <p>This is a blockquote.</p>
-
- <p>This is the second paragraph in the blockquote.</p>
-
- <h2>This is an H2 in a blockquote</h2>
- </blockquote>
-
-
-
-### Phrase Emphasis ###
-
-Markdown uses asterisks and underscores to indicate spans of emphasis.
-
-Markdown:
-
- Some of these words *are emphasized*.
- Some of these words _are emphasized also_.
-
- Use two asterisks for **strong emphasis**.
- Or, if you prefer, __use two underscores instead__.
-
-Output:
-
- <p>Some of these words <em>are emphasized</em>.
- Some of these words <em>are emphasized also</em>.</p>
-
- <p>Use two asterisks for <strong>strong emphasis</strong>.
- Or, if you prefer, <strong>use two underscores instead</strong>.</p>
-
-
-
-## Lists ##
-
-Unordered (bulleted) lists use asterisks, pluses, and hyphens (`*`,
-`+`, and `-`) as list markers. These three markers are
-interchangable; this:
-
- * Candy.
- * Gum.
- * Booze.
-
-this:
-
- + Candy.
- + Gum.
- + Booze.
-
-and this:
-
- - Candy.
- - Gum.
- - Booze.
-
-all produce the same output:
-
- <ul>
- <li>Candy.</li>
- <li>Gum.</li>
- <li>Booze.</li>
- </ul>
-
-Ordered (numbered) lists use regular numbers, followed by periods, as
-list markers:
-
- 1. Red
- 2. Green
- 3. Blue
-
-Output:
-
- <ol>
- <li>Red</li>
- <li>Green</li>
- <li>Blue</li>
- </ol>
-
-If you put blank lines between items, you'll get `<p>` tags for the
-list item text. You can create multi-paragraph list items by indenting
-the paragraphs by 4 spaces or 1 tab:
-
- * A list item.
-
- With multiple paragraphs.
-
- * Another item in the list.
-
-Output:
-
- <ul>
- <li><p>A list item.</p>
- <p>With multiple paragraphs.</p></li>
- <li><p>Another item in the list.</p></li>
- </ul>
-
-
-
-### Links ###
-
-Markdown supports two styles for creating links: *inline* and
-*reference*. With both styles, you use square brackets to delimit the
-text you want to turn into a link.
-
-Inline-style links use parentheses immediately after the link text.
-For example:
-
- This is an [example link](http://example.com/).
-
-Output:
-
- <p>This is an <a href="http://example.com/">
- example link</a>.</p>
-
-Optionally, you may include a title attribute in the parentheses:
-
- This is an [example link](http://example.com/ "With a Title").
-
-Output:
-
- <p>This is an <a href="http://example.com/" title="With a Title">
- example link</a>.</p>
-
-Reference-style links allow you to refer to your links by names, which
-you define elsewhere in your document:
-
- I get 10 times more traffic from [Google][1] than from
- [Yahoo][2] or [MSN][3].
-
- [1]: http://google.com/ "Google"
- [2]: http://search.yahoo.com/ "Yahoo Search"
- [3]: http://search.msn.com/ "MSN Search"
-
-Output:
-
- <p>I get 10 times more traffic from <a href="http://google.com/"
- title="Google">Google</a> than from <a href="http://search.yahoo.com/"
- title="Yahoo Search">Yahoo</a> or <a href="http://search.msn.com/"
- title="MSN Search">MSN</a>.</p>
-
-The title attribute is optional. Link names may contain letters,
-numbers and spaces, but are *not* case sensitive:
-
- I start my morning with a cup of coffee and
- [The New York Times][NY Times].
-
- [ny times]: http://www.nytimes.com/
-
-Output:
-
- <p>I start my morning with a cup of coffee and
- <a href="http://www.nytimes.com/">The New York Times</a>.</p>
-
-
-### Images ###
-
-Image syntax is very much like link syntax.
-
-Inline (titles are optional):
-
- 
-
-Reference-style:
-
- ![alt text][id]
-
- [id]: /path/to/img.jpg "Title"
-
-Both of the above examples produce the same output:
-
- <img src="/path/to/img.jpg" alt="alt text" title="Title" />
-
-
-
-### Code ###
-
-In a regular paragraph, you can create code span by wrapping text in
-backtick quotes. Any ampersands (`&`) and angle brackets (`<` or
-`>`) will automatically be translated into HTML entities. This makes
-it easy to use Markdown to write about HTML example code:
-
- I strongly recommend against using any `<blink>` tags.
-
- I wish SmartyPants used named entities like `—`
- instead of decimal-encoded entites like `—`.
-
-Output:
-
- <p>I strongly recommend against using any
- <code><blink></code> tags.</p>
-
- <p>I wish SmartyPants used named entities like
- <code>&mdash;</code> instead of decimal-encoded
- entites like <code>&#8212;</code>.</p>
-
-
-To specify an entire block of pre-formatted code, indent every line of
-the block by 4 spaces or 1 tab. Just like with code spans, `&`, `<`,
-and `>` characters will be escaped automatically.
-
-Markdown:
-
- If you want your page to validate under XHTML 1.0 Strict,
- you've got to put paragraph tags in your blockquotes:
-
- <blockquote>
- <p>For example.</p>
- </blockquote>
-
-Output:
-
- <p>If you want your page to validate under XHTML 1.0 Strict,
- you've got to put paragraph tags in your blockquotes:</p>
-
- <pre><code><blockquote>
- <p>For example.</p>
- </blockquote>
- </code></pre>
+++ /dev/null
-Markdown: Syntax
-================
-
-<ul id="ProjectSubmenu">
- <li><a href="/projects/markdown/" title="Markdown Project Page">Main</a></li>
- <li><a href="/projects/markdown/basics" title="Markdown Basics">Basics</a></li>
- <li><a class="selected" title="Markdown Syntax Documentation">Syntax</a></li>
- <li><a href="/projects/markdown/license" title="Pricing and License Information">License</a></li>
- <li><a href="/projects/markdown/dingus" title="Online Markdown Web Form">Dingus</a></li>
-</ul>
-
-
-* [Overview](#overview)
- * [Philosophy](#philosophy)
- * [Inline HTML](#html)
- * [Automatic Escaping for Special Characters](#autoescape)
-* [Block Elements](#block)
- * [Paragraphs and Line Breaks](#p)
- * [Headers](#header)
- * [Blockquotes](#blockquote)
- * [Lists](#list)
- * [Code Blocks](#precode)
- * [Horizontal Rules](#hr)
-* [Span Elements](#span)
- * [Links](#link)
- * [Emphasis](#em)
- * [Code](#code)
- * [Images](#img)
-* [Miscellaneous](#misc)
- * [Backslash Escapes](#backslash)
- * [Automatic Links](#autolink)
-
-
-**Note:** This document is itself written using Markdown; you
-can [see the source for it by adding '.text' to the URL][src].
-
- [src]: /projects/markdown/syntax.text
-
-* * *
-
-<h2 id="overview">Overview</h2>
-
-<h3 id="philosophy">Philosophy</h3>
-
-Markdown is intended to be as easy-to-read and easy-to-write as is feasible.
-
-Readability, however, is emphasized above all else. A Markdown-formatted
-document should be publishable as-is, as plain text, without looking
-like it's been marked up with tags or formatting instructions. While
-Markdown's syntax has been influenced by several existing text-to-HTML
-filters -- including [Setext] [1], [atx] [2], [Textile] [3], [reStructuredText] [4],
-[Grutatext] [5], and [EtText] [6] -- the single biggest source of
-inspiration for Markdown's syntax is the format of plain text email.
-
- [1]: http://docutils.sourceforge.net/mirror/setext.html
- [2]: http://www.aaronsw.com/2002/atx/
- [3]: http://textism.com/tools/textile/
- [4]: http://docutils.sourceforge.net/rst.html
- [5]: http://www.triptico.com/software/grutatxt.html
- [6]: http://ettext.taint.org/doc/
-
-To this end, Markdown's syntax is comprised entirely of punctuation
-characters, which punctuation characters have been carefully chosen so
-as to look like what they mean. E.g., asterisks around a word actually
-look like \*emphasis\*. Markdown lists look like, well, lists. Even
-blockquotes look like quoted passages of text, assuming you've ever
-used email.
-
-
-
-<h3 id="html">Inline HTML</h3>
-
-Markdown's syntax is intended for one purpose: to be used as a
-format for *writing* for the web.
-
-Markdown is not a replacement for HTML, or even close to it. Its
-syntax is very small, corresponding only to a very small subset of
-HTML tags. The idea is *not* to create a syntax that makes it easier
-to insert HTML tags. In my opinion, HTML tags are already easy to
-insert. The idea for Markdown is to make it easy to read, write, and
-edit prose. HTML is a *publishing* format; Markdown is a *writing*
-format. Thus, Markdown's formatting syntax only addresses issues that
-can be conveyed in plain text.
-
-For any markup that is not covered by Markdown's syntax, you simply
-use HTML itself. There's no need to preface it or delimit it to
-indicate that you're switching from Markdown to HTML; you just use
-the tags.
-
-The only restrictions are that block-level HTML elements -- e.g. `<div>`,
-`<table>`, `<pre>`, `<p>`, etc. -- must be separated from surrounding
-content by blank lines, and the start and end tags of the block should
-not be indented with tabs or spaces. Markdown is smart enough not
-to add extra (unwanted) `<p>` tags around HTML block-level tags.
-
-For example, to add an HTML table to a Markdown article:
-
- This is a regular paragraph.
-
- <table>
- <tr>
- <td>Foo</td>
- </tr>
- </table>
-
- This is another regular paragraph.
-
-Note that Markdown formatting syntax is not processed within block-level
-HTML tags. E.g., you can't use Markdown-style `*emphasis*` inside an
-HTML block.
-
-Span-level HTML tags -- e.g. `<span>`, `<cite>`, or `<del>` -- can be
-used anywhere in a Markdown paragraph, list item, or header. If you
-want, you can even use HTML tags instead of Markdown formatting; e.g. if
-you'd prefer to use HTML `<a>` or `<img>` tags instead of Markdown's
-link or image syntax, go right ahead.
-
-Unlike block-level HTML tags, Markdown syntax *is* processed within
-span-level tags.
-
-
-<h3 id="autoescape">Automatic Escaping for Special Characters</h3>
-
-In HTML, there are two characters that demand special treatment: `<`
-and `&`. Left angle brackets are used to start tags; ampersands are
-used to denote HTML entities. If you want to use them as literal
-characters, you must escape them as entities, e.g. `<`, and
-`&`.
-
-Ampersands in particular are bedeviling for web writers. If you want to
-write about 'AT&T', you need to write '`AT&T`'. You even need to
-escape ampersands within URLs. Thus, if you want to link to:
-
- http://images.google.com/images?num=30&q=larry+bird
-
-you need to encode the URL as:
-
- http://images.google.com/images?num=30&q=larry+bird
-
-in your anchor tag `href` attribute. Needless to say, this is easy to
-forget, and is probably the single most common source of HTML validation
-errors in otherwise well-marked-up web sites.
-
-Markdown allows you to use these characters naturally, taking care of
-all the necessary escaping for you. If you use an ampersand as part of
-an HTML entity, it remains unchanged; otherwise it will be translated
-into `&`.
-
-So, if you want to include a copyright symbol in your article, you can write:
-
- ©
-
-and Markdown will leave it alone. But if you write:
-
- AT&T
-
-Markdown will translate it to:
-
- AT&T
-
-Similarly, because Markdown supports [inline HTML](#html), if you use
-angle brackets as delimiters for HTML tags, Markdown will treat them as
-such. But if you write:
-
- 4 < 5
-
-Markdown will translate it to:
-
- 4 < 5
-
-However, inside Markdown code spans and blocks, angle brackets and
-ampersands are *always* encoded automatically. This makes it easy to use
-Markdown to write about HTML code. (As opposed to raw HTML, which is a
-terrible format for writing about HTML syntax, because every single `<`
-and `&` in your example code needs to be escaped.)
-
-
-* * *
-
-
-<h2 id="block">Block Elements</h2>
-
-
-<h3 id="p">Paragraphs and Line Breaks</h3>
-
-A paragraph is simply one or more consecutive lines of text, separated
-by one or more blank lines. (A blank line is any line that looks like a
-blank line -- a line containing nothing but spaces or tabs is considered
-blank.) Normal paragraphs should not be indented with spaces or tabs.
-
-The implication of the "one or more consecutive lines of text" rule is
-that Markdown supports "hard-wrapped" text paragraphs. This differs
-significantly from most other text-to-HTML formatters (including Movable
-Type's "Convert Line Breaks" option) which translate every line break
-character in a paragraph into a `<br />` tag.
-
-When you *do* want to insert a `<br />` break tag using Markdown, you
-end a line with two or more spaces, then type return.
-
-Yes, this takes a tad more effort to create a `<br />`, but a simplistic
-"every line break is a `<br />`" rule wouldn't work for Markdown.
-Markdown's email-style [blockquoting][bq] and multi-paragraph [list items][l]
-work best -- and look better -- when you format them with hard breaks.
-
- [bq]: #blockquote
- [l]: #list
-
-
-
-<h3 id="header">Headers</h3>
-
-Markdown supports two styles of headers, [Setext] [1] and [atx] [2].
-
-Setext-style headers are "underlined" using equal signs (for first-level
-headers) and dashes (for second-level headers). For example:
-
- This is an H1
- =============
-
- This is an H2
- -------------
-
-Any number of underlining `=`'s or `-`'s will work.
-
-Atx-style headers use 1-6 hash characters at the start of the line,
-corresponding to header levels 1-6. For example:
-
- # This is an H1
-
- ## This is an H2
-
- ###### This is an H6
-
-Optionally, you may "close" atx-style headers. This is purely
-cosmetic -- you can use this if you think it looks better. The
-closing hashes don't even need to match the number of hashes
-used to open the header. (The number of opening hashes
-determines the header level.) :
-
- # This is an H1 #
-
- ## This is an H2 ##
-
- ### This is an H3 ######
-
-
-<h3 id="blockquote">Blockquotes</h3>
-
-Markdown uses email-style `>` characters for blockquoting. If you're
-familiar with quoting passages of text in an email message, then you
-know how to create a blockquote in Markdown. It looks best if you hard
-wrap the text and put a `>` before every line:
-
- > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
- > consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
- > Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
- >
- > Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
- > id sem consectetuer libero luctus adipiscing.
-
-Markdown allows you to be lazy and only put the `>` before the first
-line of a hard-wrapped paragraph:
-
- > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
- consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
- Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
-
- > Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
- id sem consectetuer libero luctus adipiscing.
-
-Blockquotes can be nested (i.e. a blockquote-in-a-blockquote) by
-adding additional levels of `>`:
-
- > This is the first level of quoting.
- >
- > > This is nested blockquote.
- >
- > Back to the first level.
-
-Blockquotes can contain other Markdown elements, including headers, lists,
-and code blocks:
-
- > ## This is a header.
- >
- > 1. This is the first list item.
- > 2. This is the second list item.
- >
- > Here's some example code:
- >
- > return shell_exec("echo $input | $markdown_script");
-
-Any decent text editor should make email-style quoting easy. For
-example, with BBEdit, you can make a selection and choose Increase
-Quote Level from the Text menu.
-
-
-<h3 id="list">Lists</h3>
-
-Markdown supports ordered (numbered) and unordered (bulleted) lists.
-
-Unordered lists use asterisks, pluses, and hyphens -- interchangably
--- as list markers:
-
- * Red
- * Green
- * Blue
-
-is equivalent to:
-
- + Red
- + Green
- + Blue
-
-and:
-
- - Red
- - Green
- - Blue
-
-Ordered lists use numbers followed by periods:
-
- 1. Bird
- 2. McHale
- 3. Parish
-
-It's important to note that the actual numbers you use to mark the
-list have no effect on the HTML output Markdown produces. The HTML
-Markdown produces from the above list is:
-
- <ol>
- <li>Bird</li>
- <li>McHale</li>
- <li>Parish</li>
- </ol>
-
-If you instead wrote the list in Markdown like this:
-
- 1. Bird
- 1. McHale
- 1. Parish
-
-or even:
-
- 3. Bird
- 1. McHale
- 8. Parish
-
-you'd get the exact same HTML output. The point is, if you want to,
-you can use ordinal numbers in your ordered Markdown lists, so that
-the numbers in your source match the numbers in your published HTML.
-But if you want to be lazy, you don't have to.
-
-If you do use lazy list numbering, however, you should still start the
-list with the number 1. At some point in the future, Markdown may support
-starting ordered lists at an arbitrary number.
-
-List markers typically start at the left margin, but may be indented by
-up to three spaces. List markers must be followed by one or more spaces
-or a tab.
-
-To make lists look nice, you can wrap items with hanging indents:
-
- * Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
- Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
- viverra nec, fringilla in, laoreet vitae, risus.
- * Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
- Suspendisse id sem consectetuer libero luctus adipiscing.
-
-But if you want to be lazy, you don't have to:
-
- * Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
- Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
- viverra nec, fringilla in, laoreet vitae, risus.
- * Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
- Suspendisse id sem consectetuer libero luctus adipiscing.
-
-If list items are separated by blank lines, Markdown will wrap the
-items in `<p>` tags in the HTML output. For example, this input:
-
- * Bird
- * Magic
-
-will turn into:
-
- <ul>
- <li>Bird</li>
- <li>Magic</li>
- </ul>
-
-But this:
-
- * Bird
-
- * Magic
-
-will turn into:
-
- <ul>
- <li><p>Bird</p></li>
- <li><p>Magic</p></li>
- </ul>
-
-List items may consist of multiple paragraphs. Each subsequent
-paragraph in a list item must be indented by either 4 spaces
-or one tab:
-
- 1. This is a list item with two paragraphs. Lorem ipsum dolor
- sit amet, consectetuer adipiscing elit. Aliquam hendrerit
- mi posuere lectus.
-
- Vestibulum enim wisi, viverra nec, fringilla in, laoreet
- vitae, risus. Donec sit amet nisl. Aliquam semper ipsum
- sit amet velit.
-
- 2. Suspendisse id sem consectetuer libero luctus adipiscing.
-
-It looks nice if you indent every line of the subsequent
-paragraphs, but here again, Markdown will allow you to be
-lazy:
-
- * This is a list item with two paragraphs.
-
- This is the second paragraph in the list item. You're
- only required to indent the first line. Lorem ipsum dolor
- sit amet, consectetuer adipiscing elit.
-
- * Another item in the same list.
-
-To put a blockquote within a list item, the blockquote's `>`
-delimiters need to be indented:
-
- * A list item with a blockquote:
-
- > This is a blockquote
- > inside a list item.
-
-To put a code block within a list item, the code block needs
-to be indented *twice* -- 8 spaces or two tabs:
-
- * A list item with a code block:
-
- <code goes here>
-
-
-It's worth noting that it's possible to trigger an ordered list by
-accident, by writing something like this:
-
- 1986. What a great season.
-
-In other words, a *number-period-space* sequence at the beginning of a
-line. To avoid this, you can backslash-escape the period:
-
- 1986\. What a great season.
-
-
-
-<h3 id="precode">Code Blocks</h3>
-
-Pre-formatted code blocks are used for writing about programming or
-markup source code. Rather than forming normal paragraphs, the lines
-of a code block are interpreted literally. Markdown wraps a code block
-in both `<pre>` and `<code>` tags.
-
-To produce a code block in Markdown, simply indent every line of the
-block by at least 4 spaces or 1 tab. For example, given this input:
-
- This is a normal paragraph:
-
- This is a code block.
-
-Markdown will generate:
-
- <p>This is a normal paragraph:</p>
-
- <pre><code>This is a code block.
- </code></pre>
-
-One level of indentation -- 4 spaces or 1 tab -- is removed from each
-line of the code block. For example, this:
-
- Here is an example of AppleScript:
-
- tell application "Foo"
- beep
- end tell
-
-will turn into:
-
- <p>Here is an example of AppleScript:</p>
-
- <pre><code>tell application "Foo"
- beep
- end tell
- </code></pre>
-
-A code block continues until it reaches a line that is not indented
-(or the end of the article).
-
-Within a code block, ampersands (`&`) and angle brackets (`<` and `>`)
-are automatically converted into HTML entities. This makes it very
-easy to include example HTML source code using Markdown -- just paste
-it and indent it, and Markdown will handle the hassle of encoding the
-ampersands and angle brackets. For example, this:
-
- <div class="footer">
- © 2004 Foo Corporation
- </div>
-
-will turn into:
-
- <pre><code><div class="footer">
- &copy; 2004 Foo Corporation
- </div>
- </code></pre>
-
-Regular Markdown syntax is not processed within code blocks. E.g.,
-asterisks are just literal asterisks within a code block. This means
-it's also easy to use Markdown to write about Markdown's own syntax.
-
-
-
-<h3 id="hr">Horizontal Rules</h3>
-
-You can produce a horizontal rule tag (`<hr />`) by placing three or
-more hyphens, asterisks, or underscores on a line by themselves. If you
-wish, you may use spaces between the hyphens or asterisks. Each of the
-following lines will produce a horizontal rule:
-
- * * *
-
- ***
-
- *****
-
- - - -
-
- ---------------------------------------
-
- _ _ _
-
-
-* * *
-
-<h2 id="span">Span Elements</h2>
-
-<h3 id="link">Links</h3>
-
-Markdown supports two style of links: *inline* and *reference*.
-
-In both styles, the link text is delimited by [square brackets].
-
-To create an inline link, use a set of regular parentheses immediately
-after the link text's closing square bracket. Inside the parentheses,
-put the URL where you want the link to point, along with an *optional*
-title for the link, surrounded in quotes. For example:
-
- This is [an example](http://example.com/ "Title") inline link.
-
- [This link](http://example.net/) has no title attribute.
-
-Will produce:
-
- <p>This is <a href="http://example.com/" title="Title">
- an example</a> inline link.</p>
-
- <p><a href="http://example.net/">This link</a> has no
- title attribute.</p>
-
-If you're referring to a local resource on the same server, you can
-use relative paths:
-
- See my [About](/about/) page for details.
-
-Reference-style links use a second set of square brackets, inside
-which you place a label of your choosing to identify the link:
-
- This is [an example][id] reference-style link.
-
-You can optionally use a space to separate the sets of brackets:
-
- This is [an example] [id] reference-style link.
-
-Then, anywhere in the document, you define your link label like this,
-on a line by itself:
-
- [id]: http://example.com/ "Optional Title Here"
-
-That is:
-
-* Square brackets containing the link identifier (optionally
- indented from the left margin using up to three spaces);
-* followed by a colon;
-* followed by one or more spaces (or tabs);
-* followed by the URL for the link;
-* optionally followed by a title attribute for the link, enclosed
- in double or single quotes.
-
-The link URL may, optionally, be surrounded by angle brackets:
-
- [id]: <http://example.com/> "Optional Title Here"
-
-You can put the title attribute on the next line and use extra spaces
-or tabs for padding, which tends to look better with longer URLs:
-
- [id]: http://example.com/longish/path/to/resource/here
- "Optional Title Here"
-
-Link definitions are only used for creating links during Markdown
-processing, and are stripped from your document in the HTML output.
-
-Link definition names may constist of letters, numbers, spaces, and punctuation -- but they are *not* case sensitive. E.g. these two links:
-
- [link text][a]
- [link text][A]
-
-are equivalent.
-
-The *implicit link name* shortcut allows you to omit the name of the
-link, in which case the link text itself is used as the name.
-Just use an empty set of square brackets -- e.g., to link the word
-"Google" to the google.com web site, you could simply write:
-
- [Google][]
-
-And then define the link:
-
- [Google]: http://google.com/
-
-Because link names may contain spaces, this shortcut even works for
-multiple words in the link text:
-
- Visit [Daring Fireball][] for more information.
-
-And then define the link:
-
- [Daring Fireball]: http://daringfireball.net/
-
-Link definitions can be placed anywhere in your Markdown document. I
-tend to put them immediately after each paragraph in which they're
-used, but if you want, you can put them all at the end of your
-document, sort of like footnotes.
-
-Here's an example of reference links in action:
-
- I get 10 times more traffic from [Google] [1] than from
- [Yahoo] [2] or [MSN] [3].
-
- [1]: http://google.com/ "Google"
- [2]: http://search.yahoo.com/ "Yahoo Search"
- [3]: http://search.msn.com/ "MSN Search"
-
-Using the implicit link name shortcut, you could instead write:
-
- I get 10 times more traffic from [Google][] than from
- [Yahoo][] or [MSN][].
-
- [google]: http://google.com/ "Google"
- [yahoo]: http://search.yahoo.com/ "Yahoo Search"
- [msn]: http://search.msn.com/ "MSN Search"
-
-Both of the above examples will produce the following HTML output:
-
- <p>I get 10 times more traffic from <a href="http://google.com/"
- title="Google">Google</a> than from
- <a href="http://search.yahoo.com/" title="Yahoo Search">Yahoo</a>
- or <a href="http://search.msn.com/" title="MSN Search">MSN</a>.</p>
-
-For comparison, here is the same paragraph written using
-Markdown's inline link style:
-
- I get 10 times more traffic from [Google](http://google.com/ "Google")
- than from [Yahoo](http://search.yahoo.com/ "Yahoo Search") or
- [MSN](http://search.msn.com/ "MSN Search").
-
-The point of reference-style links is not that they're easier to
-write. The point is that with reference-style links, your document
-source is vastly more readable. Compare the above examples: using
-reference-style links, the paragraph itself is only 81 characters
-long; with inline-style links, it's 176 characters; and as raw HTML,
-it's 234 characters. In the raw HTML, there's more markup than there
-is text.
-
-With Markdown's reference-style links, a source document much more
-closely resembles the final output, as rendered in a browser. By
-allowing you to move the markup-related metadata out of the paragraph,
-you can add links without interrupting the narrative flow of your
-prose.
-
-
-<h3 id="em">Emphasis</h3>
-
-Markdown treats asterisks (`*`) and underscores (`_`) as indicators of
-emphasis. Text wrapped with one `*` or `_` will be wrapped with an
-HTML `<em>` tag; double `*`'s or `_`'s will be wrapped with an HTML
-`<strong>` tag. E.g., this input:
-
- *single asterisks*
-
- _single underscores_
-
- **double asterisks**
-
- __double underscores__
-
-will produce:
-
- <em>single asterisks</em>
-
- <em>single underscores</em>
-
- <strong>double asterisks</strong>
-
- <strong>double underscores</strong>
-
-You can use whichever style you prefer; the lone restriction is that
-the same character must be used to open and close an emphasis span.
-
-Emphasis can be used in the middle of a word:
-
- un*fucking*believable
-
-But if you surround an `*` or `_` with spaces, it'll be treated as a
-literal asterisk or underscore.
-
-To produce a literal asterisk or underscore at a position where it
-would otherwise be used as an emphasis delimiter, you can backslash
-escape it:
-
- \*this text is surrounded by literal asterisks\*
-
-
-
-<h3 id="code">Code</h3>
-
-To indicate a span of code, wrap it with backtick quotes (`` ` ``).
-Unlike a pre-formatted code block, a code span indicates code within a
-normal paragraph. For example:
-
- Use the `printf()` function.
-
-will produce:
-
- <p>Use the <code>printf()</code> function.</p>
-
-To include a literal backtick character within a code span, you can use
-multiple backticks as the opening and closing delimiters:
-
- ``There is a literal backtick (`) here.``
-
-which will produce this:
-
- <p><code>There is a literal backtick (`) here.</code></p>
-
-The backtick delimiters surrounding a code span may include spaces --
-one after the opening, one before the closing. This allows you to place
-literal backtick characters at the beginning or end of a code span:
-
- A single backtick in a code span: `` ` ``
-
- A backtick-delimited string in a code span: `` `foo` ``
-
-will produce:
-
- <p>A single backtick in a code span: <code>`</code></p>
-
- <p>A backtick-delimited string in a code span: <code>`foo`</code></p>
-
-With a code span, ampersands and angle brackets are encoded as HTML
-entities automatically, which makes it easy to include example HTML
-tags. Markdown will turn this:
-
- Please don't use any `<blink>` tags.
-
-into:
-
- <p>Please don't use any <code><blink></code> tags.</p>
-
-You can write this:
-
- `—` is the decimal-encoded equivalent of `—`.
-
-to produce:
-
- <p><code>&#8212;</code> is the decimal-encoded
- equivalent of <code>&mdash;</code>.</p>
-
-
-
-<h3 id="img">Images</h3>
-
-Admittedly, it's fairly difficult to devise a "natural" syntax for
-placing images into a plain text document format.
-
-Markdown uses an image syntax that is intended to resemble the syntax
-for links, allowing for two styles: *inline* and *reference*.
-
-Inline image syntax looks like this:
-
- 
-
- 
-
-That is:
-
-* An exclamation mark: `!`;
-* followed by a set of square brackets, containing the `alt`
- attribute text for the image;
-* followed by a set of parentheses, containing the URL or path to
- the image, and an optional `title` attribute enclosed in double
- or single quotes.
-
-Reference-style image syntax looks like this:
-
- ![Alt text][id]
-
-Where "id" is the name of a defined image reference. Image references
-are defined using syntax identical to link references:
-
- [id]: url/to/image "Optional title attribute"
-
-As of this writing, Markdown has no syntax for specifying the
-dimensions of an image; if this is important to you, you can simply
-use regular HTML `<img>` tags.
-
-
-* * *
-
-
-<h2 id="misc">Miscellaneous</h2>
-
-<h3 id="autolink">Automatic Links</h3>
-
-Markdown supports a shortcut style for creating "automatic" links for URLs and email addresses: simply surround the URL or email address with angle brackets. What this means is that if you want to show the actual text of a URL or email address, and also have it be a clickable link, you can do this:
-
- <http://example.com/>
-
-Markdown will turn this into:
-
- <a href="http://example.com/">http://example.com/</a>
-
-Automatic links for email addresses work similarly, except that
-Markdown will also perform a bit of randomized decimal and hex
-entity-encoding to help obscure your address from address-harvesting
-spambots. For example, Markdown will turn this:
-
- <address@example.com>
-
-into something like this:
-
- <a href="mailto:addre
- ss@example.co
- m">address@exa
- mple.com</a>
-
-which will render in a browser as a clickable link to "address@example.com".
-
-(This sort of entity-encoding trick will indeed fool many, if not
-most, address-harvesting bots, but it definitely won't fool all of
-them. It's better than nothing, but an address published in this way
-will probably eventually start receiving spam.)
-
-
-
-<h3 id="backslash">Backslash Escapes</h3>
-
-Markdown allows you to use backslash escapes to generate literal
-characters which would otherwise have special meaning in Markdown's
-formatting syntax. For example, if you wanted to surround a word with
-literal asterisks (instead of an HTML `<em>` tag), you can backslashes
-before the asterisks, like this:
-
- \*literal asterisks\*
-
-Markdown provides backslash escapes for the following characters:
-
- \ backslash
- ` backtick
- * asterisk
- _ underscore
- {} curly braces
- [] square brackets
- () parentheses
- # hash mark
- + plus sign
- - minus sign (hyphen)
- . dot
- ! exclamation mark
-
+++ /dev/null
-> foo
->
-> > bar
->
-> foo
+++ /dev/null
-## Unordered
-
-Asterisks tight:
-
-* asterisk 1
-* asterisk 2
-* asterisk 3
-
-
-Asterisks loose:
-
-* asterisk 1
-
-* asterisk 2
-
-* asterisk 3
-
-* * *
-
-Pluses tight:
-
-+ Plus 1
-+ Plus 2
-+ Plus 3
-
-
-Pluses loose:
-
-+ Plus 1
-
-+ Plus 2
-
-+ Plus 3
-
-* * *
-
-
-Minuses tight:
-
-- Minus 1
-- Minus 2
-- Minus 3
-
-
-Minuses loose:
-
-- Minus 1
-
-- Minus 2
-
-- Minus 3
-
-
-## Ordered
-
-Tight:
-
-1. First
-2. Second
-3. Third
-
-and:
-
-1. One
-2. Two
-3. Three
-
-
-Loose using tabs:
-
-1. First
-
-2. Second
-
-3. Third
-
-and using spaces:
-
-1. One
-
-2. Two
-
-3. Three
-
-Multiple paragraphs:
-
-1. Item 1, graf one.
-
- Item 2. graf two. The quick brown fox jumped over the lazy dog's
- back.
-
-2. Item 2.
-
-3. Item 3.
-
-
-
-## Nested
-
-* Tab
- * Tab
- * Tab
-
-Here's another:
-
-1. First
-2. Second:
- * Fee
- * Fie
- * Foe
-3. Third
-
-Same thing but with paragraphs:
-
-1. First
-
-2. Second:
- * Fee
- * Fie
- * Foe
-
-3. Third
-
-
-This was an error in Markdown 1.0.1:
-
-* this
-
- * sub
-
- that
+++ /dev/null
-***This is strong and em.***
-
-So is ***this*** word.
-
-___This is strong and em.___
-
-So is ___this___ word.
+++ /dev/null
-+ this is a list item
- indented with tabs
-
-+ this is a list item
- indented with spaces
-
-Code:
-
- this code block is indented by one tab
-
-And:
-
- this code block is indented by two tabs
-
-And:
-
- + this is an example list item
- indented with tabs
-
- + this is an example list item
- indented with spaces
+++ /dev/null
-> A list within a blockquote:
->
-> * asterisk 1
-> * asterisk 2
-> * asterisk 3
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Python-Markdown Regression Tests
================================
-Tests of the various APIs with the python markdown lib.
+Tests of the various APIs with the Python Markdown library.
"""
import unittest
self.parser = markdown.Markdown().parser
def testParseChunk(self):
- """ Test BlockParser.parseChunk. """
+ """ Test `BlockParser.parseChunk`. """
root = etree.Element("div")
text = 'foo'
self.parser.parseChunk(root, text)
)
def testParseDocument(self):
- """ Test BlockParser.parseDocument. """
+ """ Test `BlockParser.parseDocument`. """
lines = ['#foo', '', 'bar', '', ' baz']
tree = self.parser.parseDocument(lines)
self.assertIsInstance(tree, etree.ElementTree)
class TestBlockParserState(unittest.TestCase):
- """ Tests of the State class for BlockParser. """
+ """ Tests of the State class for `BlockParser`. """
def setUp(self):
self.state = markdown.blockparser.State()
self.assertEqual(self.state, ['a_state', 'state2'])
def testIsSate(self):
- """ Test State.isstate(). """
+ """ Test `State.isstate()`. """
self.assertEqual(self.state.isstate('anything'), False)
self.state.set('a_state')
self.assertEqual(self.state.isstate('a_state'), True)
self.assertEqual(self.state.isstate('missing'), False)
def testReset(self):
- """ Test State.reset(). """
+ """ Test `State.reset()`. """
self.state.set('a_state')
self.state.reset()
self.assertEqual(self.state, [])
class TestHtmlStash(unittest.TestCase):
- """ Test Markdown's HtmlStash. """
+ """ Test Markdown's `HtmlStash`. """
def setUp(self):
self.stash = markdown.util.HtmlStash()
self.placeholder = self.stash.store('foo')
def testSimpleStore(self):
- """ Test HtmlStash.store. """
+ """ Test `HtmlStash.store`. """
self.assertEqual(self.placeholder, self.stash.get_placeholder(0))
self.assertEqual(self.stash.html_counter, 1)
self.assertEqual(self.stash.rawHtmlBlocks, ['foo'])
def testStoreMore(self):
- """ Test HtmlStash.store with additional blocks. """
+ """ Test `HtmlStash.store` with additional blocks. """
placeholder = self.stash.store('bar')
self.assertEqual(placeholder, self.stash.get_placeholder(1))
self.assertEqual(self.stash.html_counter, 2)
)
def testReset(self):
- """ Test HtmlStash.reset. """
+ """ Test `HtmlStash.reset`. """
self.stash.reset()
self.assertEqual(self.stash.html_counter, 0)
self.assertEqual(self.stash.rawHtmlBlocks, [])
class Item:
- """ A dummy Registry item object for testing. """
+ """ A dummy `Registry` item object for testing. """
def __init__(self, data):
self.data = data
self.assertEqual(len(r), 2)
r.deregister('c', strict=False)
self.assertEqual(len(r), 1)
- # deregister non-existent item with strict=False
+ # deregister non-existent item with `strict=False`
r.deregister('d', strict=False)
self.assertEqual(len(r), 1)
with self.assertRaises(ValueError):
- # deregister non-existent item with strict=True
+ # deregister non-existent item with `strict=True`
r.deregister('e')
self.assertEqual(list(r), ['a'])
r = markdown.util.Registry()
with self.assertRaises(TypeError):
r[0] = 'a'
- # TODO: restore this when deprecated __setitem__ is removed.
- # with self.assertRaises(TypeError):
- # r['a'] = 'a'
- # TODO: remove this when deprecated __setitem__ is removed.
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter("always")
-
- r['a'] = Item('a')
- self.assertEqual(list(r), ['a'])
- r['b'] = Item('b')
- self.assertEqual(list(r), ['a', 'b'])
- r['a'] = Item('a1')
- self.assertEqual(list(r), ['a1', 'b'])
-
- # Check the warnings
- self.assertEqual(len(w), 3)
- self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w))
+ with self.assertRaises(TypeError):
+ r['a'] = 'a'
def testRegistryDelItem(self):
r = markdown.util.Registry()
r.register(Item('a'), 'a', 20)
- with self.assertRaises(KeyError):
+ with self.assertRaises(TypeError):
del r[0]
- # TODO: restore this when deprecated __del__ is removed.
- # with self.assertRaises(TypeError):
- # del r['a']
- # TODO: remove this when deprecated __del__ is removed.
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter("always")
-
- r.register(Item('b'), 'b', 15)
- r.register(Item('c'), 'c', 10)
- del r['b']
- self.assertEqual(list(r), ['a', 'c'])
+ with self.assertRaises(TypeError):
del r['a']
- self.assertEqual(list(r), ['c'])
- with self.assertRaises(KeyError):
- del r['badname']
- del r['c']
- self.assertEqual(list(r), [])
-
- # Check the warnings
- self.assertEqual(len(w), 3)
- self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w))
def testRegistrySlice(self):
r = markdown.util.Registry()
self.assertEqual(len(r), 2)
self.assertEqual(list(r), ['b2', 'a'])
- def testRegistryDeprecatedAdd(self):
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter("always")
-
- r = markdown.util.Registry()
- # Add first item
- r.add('c', Item('c'), '_begin')
- self.assertEqual(list(r), ['c'])
- # Added to beginning
- r.add('b', Item('b'), '_begin')
- self.assertEqual(list(r), ['b', 'c'])
- # Add before first item
- r.add('a', Item('a'), '<b')
- self.assertEqual(list(r), ['a', 'b', 'c'])
- # Add before non-first item
- r.add('a1', Item('a1'), '<b')
- self.assertEqual(list(r), ['a', 'a1', 'b', 'c'])
- # Add after non-last item
- r.add('b1', Item('b1'), '>b')
- self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c'])
- # Add after last item
- r.add('d', Item('d'), '>c')
- self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c', 'd'])
- # Add to end
- r.add('e', Item('e'), '_end')
- self.assertEqual(list(r), ['a', 'a1', 'b', 'b1', 'c', 'd', 'e'])
- with self.assertRaises(ValueError):
- r.add('f', Item('f'), 'badlocation')
-
- # Check the warnings
- self.assertEqual(len(w), 7)
- self.assertTrue(all(issubclass(x.category, DeprecationWarning) for x in w))
-
class TestErrors(unittest.TestCase):
""" Test Error Reporting. """
)
def testBaseExtention(self):
- """ Test that the base Extension class will raise NotImplemented. """
+ """ Test that the base Extension class will raise `NotImplemented`. """
self.assertRaises(
NotImplementedError,
markdown.Markdown, extensions=[markdown.extensions.Extension()]
class testETreeComments(unittest.TestCase):
"""
- Test that ElementTree Comments work.
+ Test that `ElementTree` Comments work.
- These tests should only be a concern when using cElementTree with third
+ These tests should only be a concern when using `cElementTree` with third
party serializers (including markdown's (x)html serializer). While markdown
- doesn't use ElementTree.Comment itself, we should certainly support any
+ doesn't use `ElementTree.Comment` itself, we should certainly support any
third party extensions which may. Therefore, these tests are included to
ensure such support is maintained.
"""
self.comment = etree.Comment('foo')
def testCommentIsComment(self):
- """ Test that an ElementTree Comment passes the `is Comment` test. """
+ """ Test that an `ElementTree` `Comment` passes the `is Comment` test. """
self.assertIs(self.comment.tag, etree.Comment)
def testCommentIsBlockLevel(self):
- """ Test that an ElementTree Comment is recognized as BlockLevel. """
+ """ Test that an `ElementTree` `Comment` is recognized as `BlockLevel`. """
md = markdown.Markdown()
self.assertIs(md.is_block_level(self.comment.tag), False)
def testCommentSerialization(self):
- """ Test that an ElementTree Comment serializes properly. """
+ """ Test that an `ElementTree` `Comment` serializes properly. """
self.assertEqual(
markdown.serializers.to_html_string(self.comment),
'<!--foo-->'
)
def testCommentPrettify(self):
- """ Test that an ElementTree Comment is prettified properly. """
+ """ Test that an `ElementTree` `Comment` is prettified properly. """
pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown())
pretty.run(self.comment)
self.assertEqual(
self.pretty = markdown.treeprocessors.PrettifyTreeprocessor(markdown.Markdown())
def testBrTailNoNewline(self):
- """ Test that last <br> in tree has a new line tail """
+ """ Test that last `<br>` in tree has a new line tail """
root = etree.Element('root')
br = etree.SubElement(root, 'br')
self.assertEqual(br.tail, None)
self.assertEqual(br.tail, "\n")
+class testElementPreCodeTests(unittest.TestCase):
+ """ Element `PreCode` Tests """
+ def setUp(self):
+ md = markdown.Markdown()
+ self.pretty = markdown.treeprocessors.PrettifyTreeprocessor(md)
+
+ def prettify(self, xml):
+ root = etree.fromstring(xml)
+ self.pretty.run(root)
+ return etree.tostring(root, encoding="unicode", short_empty_elements=False)
+
+ def testPreCodeEmpty(self):
+ xml = "<pre><code></code></pre>"
+ expected = "<pre><code></code></pre>\n"
+ self.assertEqual(expected, self.prettify(xml))
+
+ def testPreCodeWithChildren(self):
+ xml = "<pre><code> <span /></code></pre>"
+ expected = "<pre><code> <span></span></code></pre>\n"
+ self.assertEqual(expected, self.prettify(xml))
+
+ def testPreCodeWithSpaceOnly(self):
+ xml = "<pre><code> </code></pre>"
+ expected = "<pre><code>\n</code></pre>\n"
+ self.assertEqual(expected, self.prettify(xml))
+
+ def testPreCodeWithText(self):
+ xml = "<pre><code> hello</code></pre>"
+ expected = "<pre><code> hello\n</code></pre>\n"
+ self.assertEqual(expected, self.prettify(xml))
+
+ def testPreCodeWithTrailingSpace(self):
+ xml = "<pre><code> hello </code></pre>"
+ expected = "<pre><code> hello\n</code></pre>\n"
+ self.assertEqual(expected, self.prettify(xml))
+
+
class testSerializers(unittest.TestCase):
""" Test the html and xhtml serializers. """
)
def testProsessingInstruction(self):
- """ Test serialization of ProcessignInstruction. """
+ """ Test serialization of `ProcessignInstruction`. """
pi = ProcessingInstruction('foo', text='<&"test\nescaping">')
self.assertIs(pi.tag, ProcessingInstruction)
self.assertEqual(
)
def testQNameTag(self):
- """ Test serialization of QName tag. """
+ """ Test serialization of `QName` tag. """
div = etree.Element('div')
qname = etree.QName('http://www.w3.org/1998/Math/MathML', 'math')
math = etree.SubElement(div, qname)
)
def testQNameAttribute(self):
- """ Test serialization of QName attribute. """
+ """ Test serialization of `QName` attribute. """
div = etree.Element('div')
div.set(etree.QName('foo'), etree.QName('bar'))
self.assertEqual(
)
def testBadQNameTag(self):
- """ Test serialization of QName with no tag. """
+ """ Test serialization of `QName` with no tag. """
qname = etree.QName('http://www.w3.org/1998/Math/MathML')
el = etree.Element(qname)
self.assertRaises(ValueError, markdown.serializers.to_xhtml_string, el)
def testQNameEscaping(self):
- """ Test QName escaping. """
+ """ Test `QName` escaping. """
qname = etree.QName('<&"test\nescaping">', 'div')
el = etree.Element(qname)
self.assertEqual(
)
def testQNamePreEscaping(self):
- """ Test QName that is already partially escaped. """
+ """ Test `QName` that is already partially escaped. """
qname = etree.QName('<&"test escaping">', 'div')
el = etree.Element(qname)
self.assertEqual(
)
def buildExtension(self):
- """ Build an extension which registers fakeSerializer. """
+ """ Build an extension which registers `fakeSerializer`. """
def fakeSerializer(elem):
- # Ignore input and return hardcoded output
+ # Ignore input and return hard-coded output
return '<div><p>foo</p></div>'
class registerFakeSerializer(markdown.extensions.Extension):
class testAtomicString(unittest.TestCase):
- """ Test that AtomicStrings are honored (not parsed). """
+ """ Test that `AtomicStrings` are honored (not parsed). """
def setUp(self):
md = markdown.Markdown()
)
def testSimpleAtomicString(self):
- """ Test that a simple AtomicString is not parsed. """
+ """ Test that a simple `AtomicString` is not parsed. """
tree = etree.Element('div')
p = etree.SubElement(tree, 'p')
p.text = markdown.util.AtomicString('some *text*')
)
def testNestedAtomicString(self):
- """ Test that a nested AtomicString is not parsed. """
+ """ Test that a nested `AtomicString` is not parsed. """
tree = etree.Element('div')
p = etree.SubElement(tree, 'p')
p.text = markdown.util.AtomicString('*some* ')
self.assertEqual(options, self.default_options)
def create_config_file(self, config):
- """ Helper to create temp config files. """
+ """ Helper to create temporary configuration files. """
if not isinstance(config, str):
# convert to string
config = yaml.dump(config)
class TestBlockAppend(unittest.TestCase):
- """ Tests block kHTML append. """
+ """ Tests block `kHTML` append. """
def testBlockAppend(self):
""" Test that appended escapes are only in the current instance. """
self.md.reset()
self.assertEqual(self.md.convert(test), result)
-
-
-class TestGeneralDeprecations(unittest.TestCase):
- """Test general deprecations."""
-
- def test_version_deprecation(self):
- """Test that version is deprecated."""
-
- with warnings.catch_warnings(record=True) as w:
- # Cause all warnings to always be triggered.
- warnings.simplefilter("always")
- # Trigger a warning.
- version = markdown.version
- # Verify some things
- self.assertEqual(len(w), 1)
- self.assertTrue(issubclass(w[-1].category, DeprecationWarning))
- self.assertEqual(version, markdown.__version__)
-
- def test_version_info_deprecation(self):
- """Test that version info is deprecated."""
-
- with warnings.catch_warnings(record=True) as w:
- # Cause all warnings to always be triggered.
- warnings.simplefilter("always")
- # Trigger a warning.
- version_info = markdown.version_info
- # Verify some things
- self.assertEqual(len(w), 1)
- self.assertTrue(issubclass(w[-1].category, DeprecationWarning))
- self.assertEqual(version_info, markdown.__version_info__)
-
- def test_deprecation_wrapper_dir(self):
- """Tests the `__dir__` attribute of the class as it replaces the module's."""
-
- dir_attr = dir(markdown)
- self.assertNotIn('version', dir_attr)
- self.assertIn('__version__', dir_attr)
- self.assertNotIn('version_info', dir_attr)
- self.assertIn('__version_info__', dir_attr)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
==========================================
A collection of regression tests to confirm that the included extensions
-continue to work as advertised. This used to be accomplished by doctests.
+continue to work as advertised. This used to be accomplished by `doctests`.
"""
import unittest
self.assertEqual(self.ext.getConfigs(), {'foo': 'baz', 'bar': 'baz'})
def testSetConfigWithBadKey(self):
- # self.ext.setConfig('bad', 'baz) ==> KeyError
+ # `self.ext.setConfig('bad', 'baz)` => `KeyError`
self.assertRaises(KeyError, self.ext.setConfig, 'bad', 'baz')
def testConfigAsKwargsOnInit(self):
class TestMetaData(unittest.TestCase):
- """ Test MetaData extension. """
+ """ Test `MetaData` extension. """
def setUp(self):
self.md = markdown.Markdown(extensions=['meta'])
class TestWikiLinks(unittest.TestCase):
- """ Test Wikilinks Extension. """
+ """ Test `Wikilinks` Extension. """
def setUp(self):
self.md = markdown.Markdown(extensions=['wikilinks'])
self.text = "Some text with a [[WikiLink]]."
def testBasicWikilinks(self):
- """ Test [[wikilinks]]. """
+ """ Test `[[wikilinks]]`. """
self.assertEqual(
self.md.convert(self.text),
)
def testWikilinkWhitespace(self):
- """ Test whitespace in wikilinks. """
+ """ Test whitespace in `wikilinks`. """
self.assertEqual(
self.md.convert('[[ foo bar_baz ]]'),
'<p><a class="wikilink" href="/foo_bar_baz/">foo bar_baz</a></p>'
)
def testWikilinksMetaData(self):
- """ test MetaData with Wikilinks Extension. """
+ """ test `MetaData` with `Wikilinks` Extension. """
text = """wiki_base_url: http://example.com/
wiki_end_url: .html
'<a href="http://example.com/WikiLink.html">WikiLink</a>.</p>'
)
- # MetaData should not carry over to next document:
+ # `MetaData` should not carry over to next document:
self.assertEqual(
md.convert("No [[MetaData]] here."),
'<p>No <a class="wikilink" href="/MetaData/">MetaData</a> '
)
def testWithAttrList(self):
- """ Test TOC with attr_list Extension. """
+ """ Test TOC with `attr_list` Extension. """
md = markdown.Markdown(extensions=['toc', 'attr_list'])
text = ('# Header 1\n\n'
'## Header 2 { #foo }\n\n'
'<h1 id="toc"><em>[TOC]</em></h1>' # noqa
)
+ def testPermalink(self):
+ """ Test TOC `permalink` feature. """
+ text = '# Hd 1\n\n## Hd 2'
+ md = markdown.Markdown(
+ extensions=[markdown.extensions.toc.TocExtension(
+ permalink=True, permalink_title="PL")]
+ )
+ self.assertEqual(
+ md.convert(text),
+ '<h1 id="hd-1">'
+ 'Hd 1' # noqa
+ '<a class="headerlink" href="#hd-1" title="PL">' # noqa
+ '¶' # noqa
+ '</a>' # noqa
+ '</h1>\n'
+ '<h2 id="hd-2">'
+ 'Hd 2' # noqa
+ '<a class="headerlink" href="#hd-2" title="PL">' # noqa
+ '¶' # noqa
+ '</a>' # noqa
+ '</h2>'
+ )
+
+ def testPermalinkLeading(self):
+ """ Test TOC `permalink` with `permalink_leading` option. """
+ text = '# Hd 1\n\n## Hd 2'
+ md = markdown.Markdown(extensions=[
+ markdown.extensions.toc.TocExtension(
+ permalink=True, permalink_title="PL", permalink_leading=True)]
+ )
+ self.assertEqual(
+ md.convert(text),
+ '<h1 id="hd-1">'
+ '<a class="headerlink" href="#hd-1" title="PL">' # noqa
+ '¶' # noqa
+ '</a>' # noqa
+ 'Hd 1' # noqa
+ '</h1>\n'
+ '<h2 id="hd-2">'
+ '<a class="headerlink" href="#hd-2" title="PL">' # noqa
+ '¶' # noqa
+ '</a>' # noqa
+ 'Hd 2' # noqa
+ '</h2>'
+ )
+
+ def testInlineMarkupPermalink(self):
+ """ Test TOC `permalink` with headers containing markup. """
+ text = '# Code `in` hd'
+ md = markdown.Markdown(
+ extensions=[markdown.extensions.toc.TocExtension(
+ permalink=True, permalink_title="PL")]
+ )
+ self.assertEqual(
+ md.convert(text),
+ '<h1 id="code-in-hd">'
+ 'Code <code>in</code> hd' # noqa
+ '<a class="headerlink" href="#code-in-hd" title="PL">' # noqa
+ '¶' # noqa
+ '</a>' # noqa
+ '</h1>'
+ )
+
+ def testInlineMarkupPermalinkLeading(self):
+ """ Test TOC `permalink_leading` with headers containing markup. """
+ text = '# Code `in` hd'
+ md = markdown.Markdown(extensions=[
+ markdown.extensions.toc.TocExtension(
+ permalink=True, permalink_title="PL", permalink_leading=True)]
+ )
+ self.assertEqual(
+ md.convert(text),
+ '<h1 id="code-in-hd">'
+ '<a class="headerlink" href="#code-in-hd" title="PL">' # noqa
+ '¶' # noqa
+ '</a>' # noqa
+ 'Code <code>in</code> hd' # noqa
+ '</h1>'
+ )
+
class TestSmarty(unittest.TestCase):
def setUp(self):
'ndash': '\u2013',
'mdash': '\u2014',
'ellipsis': '\u2026',
- 'left-single-quote': '‚', # sb is not a typo!
+ 'left-single-quote': '‚', # `sb` is not a typo!
'right-single-quote': '‘',
'left-double-quote': '„',
'right-double-quote': '“',
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Quotes in attributes: attributes get output in different order
- Inline HTML (Span): Backtick in raw HTML attribute TODO: fixme
+ Inline HTML (Span): Backtick in raw HTML attribute TODO: fix me
Backslash escapes: Weird whitespace issue in output
- Ins & del: Our behavior follows markdown.pl I think PHP is wrong here
+ `Ins` & `del`: Our behavior follows `markdown.pl`. I think PHP is wrong here
- Auto Links: TODO: fix raw HTML so is doesn't match <hr@example.com> as a <hr>.
+ Auto Links: TODO: fix raw HTML so is doesn't match <hr@example.com> as a `<hr>`.
- Empty List Item: We match markdown.pl here. Maybe someday we'll support this
+ Empty List Item: We match `markdown.pl` here. Maybe someday we'll support this
Headers: TODO: fix headers to not require blank line before
- Mixed OLs and ULs: We match markdown.pl here. I think PHP is wrong here
+ Mixed `OL`s and `UL`s: We match `markdown.pl` here. I think PHP is wrong here
Emphasis: We have various minor differences in combined & incorrect em markup.
Maybe fix a few of them - but most aren't too important
- Code block in a list item: We match markdown.pl - not sure how php gets that output??
+ Code block in a list item: We match `markdown.pl` - not sure how PHP gets that output??
PHP-Specific Bugs: Not sure what to make of the escaping stuff here.
- Why is PHP not removing a blackslash?
+ Why is PHP not removing a backslash?
"""
location = os.path.join(parent_test_dir, 'php')
normalize = True
]
-# class TestPhpExtra(LegacyTestCase):
-# location = os.path.join(parent_test_dir, 'php/extra')
-# normalize = True
-# input_ext = '.text'
-# output_ext = '.xhtml'
-# default_kwargs = Kwargs(extensions=['extra'])
-
-
class TestPl2004(LegacyTestCase):
location = os.path.join(parent_test_dir, 'pl/Tests_2004')
normalize = True
Code Blocks: some weird whitespace issue
- Links, reference style: weird issue with nested brackets TODO: fixme
+ Links, reference style: weird issue with nested brackets TODO: fix me
- Backslash escapes: backticks in raw html attributes TODO: fixme
+ Backslash escapes: backticks in raw html attributes TODO: fix me
- Code Spans: more backticks in raw html attributes TODO: fixme
+ Code Spans: more backticks in raw html attributes TODO: fix me
"""
location = os.path.join(parent_test_dir, 'pl/Tests_2007')
normalize = True
admonition = Kwargs(extensions=['admonition'])
- smarty = Kwargs(
- extensions=['smarty'],
- extension_configs={'smarty': {'smart_angled_quotes': True}}
- )
-
class TestExtensionsExtra(LegacyTestCase):
location = os.path.join(parent_test_dir, 'extensions/extra')
footnotes = Kwargs(extensions=['footnotes'])
- tables = Kwargs(extensions=['tables'])
-
extra_config = Kwargs(
extensions=['extra'],
extension_configs={
try:
import packaging.version
except ImportError:
- from pkg_resources.extern import packaging
+ self.skipTest('packaging does not appear to be installed')
self.assertEqual(__version__, str(packaging.version.Version(__version__)))
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2020 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
def test_placeholder_in_source(self):
# This should never occur, but third party extensions could create weird edge cases.
md = markdown.Markdown()
- # Ensure there is an htmlstash so relevant code (nested in `if replacements`) is run.
+ # Ensure there is an `htmlstash` so relevant code (nested in `if replacements`) is run.
md.htmlStash.store('foo')
# Run with a placeholder which is not in the stash
placeholder = md.htmlStash.get_placeholder(md.htmlStash.html_counter + 1)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
),
extensions=['admonition']
)
+
+ def test_admonition_first_indented(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ '''
+ !!! danger "This is not"
+ one long admonition title
+ '''
+ ),
+ self.dedent(
+ '''
+ <div class="admonition danger">
+ <p class="admonition-title">This is not</p>
+ <pre><code>one long admonition title
+ </code></pre>
+ </div>
+ '''
+ ),
+ extensions=['admonition']
+ )
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2020 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
maxDiff = None
- # TODO: Move the rest of the attr_list tests here.
+ # TODO: Move the rest of the `attr_list` tests here.
def test_empty_list(self):
self.assertMarkdownRenders(
except ImportError:
has_pygments = False
-# The version required by the tests is the version specified and installed in the 'pygments' tox env.
-# In any environment where the PYGMENTS_VERSION environment variable is either not defined or doesn't
-# match the version of Pygments installed, all tests which rely in pygments will be skipped.
+# The version required by the tests is the version specified and installed in the `pygments` tox environment.
+# In any environment where the `PYGMENTS_VERSION` environment variable is either not defined or doesn't
+# match the version of Pygments installed, all tests which rely in Pygments will be skipped.
required_pygments_version = os.environ.get('PYGMENTS_VERSION', '')
def test_codehilite_defaults(self):
if has_pygments:
- # Odd result as no lang given and a single comment is not enough for guessing.
+ # Odd result as no `lang` given and a single comment is not enough for guessing.
expected = (
'<div class="codehilite"><pre><span></span><code><span class="err"># A Code Comment</span>\n'
'</code></pre></div>'
def test_codehilite_set_lang(self):
if has_pygments:
- # Note an extra `<span class="x">` is added to end of code block when lang explicitly set.
+ # Note an extra `<span class="x">` is added to end of code block when `lang` explicitly set.
# Compare with expected output for `test_guess_lang`. Not sure why this happens.
expected = (
'<div class="codehilite"><pre><span></span><code><span class="cp"><?php</span> '
'</code></pre></div>'
)
else:
- # Note that without pygments there is no way to check that the language name is bad.
+ # Note that without Pygments there is no way to check that the language name is bad.
expected = (
'<pre class="codehilite"><code class="language-unkown">'
'<?php print("Hello World"); ?>\n'
'</code></pre></div>'
)
else:
- # TODO: Implement linenostart for no-pygments. Will need to check what JS libs look for.
+ # TODO: Implement `linenostart` for no-Pygments. Will need to check what JavaScript libraries look for.
expected = (
'<pre class="codehilite"><code class="language-text linenums">plain text\n'
'</code></pre>'
if has_pygments and pygments.__version__ != required_pygments_version:
self.skipTest(f'Pygments=={required_pygments_version} is required')
+ # Define a custom Pygments formatter (same example in the documentation)
+ if has_pygments:
+ class CustomAddLangHtmlFormatter(pygments.formatters.HtmlFormatter):
+ def __init__(self, lang_str='', **options):
+ super().__init__(**options)
+ self.lang_str = lang_str
+
+ def _wrap_code(self, source):
+ yield 0, f'<code class="{self.lang_str}">'
+ yield from source
+ yield 0, '</code>'
+ else:
+ CustomAddLangHtmlFormatter = None
+
+ self.custom_pygments_formatter = CustomAddLangHtmlFormatter
+
maxDiff = None
def testBasicCodeHilite(self):
if has_pygments:
- # Odd result as no lang given and a single comment is not enough for guessing.
+ # Odd result as no `lang` given and a single comment is not enough for guessing.
expected = (
'<div class="codehilite"><pre><span></span><code><span class="err"># A Code Comment</span>\n'
'</code></pre></div>'
def testUnknownOption(self):
if has_pygments:
- # Odd result as no lang given and a single comment is not enough for guessing.
+ # Odd result as no `lang` given and a single comment is not enough for guessing.
expected = (
'<div class="codehilite"><pre><span></span><code><span class="err"># A Code Comment</span>\n'
'</code></pre></div>'
expected,
extensions=[CodeHiliteExtension(pygments_style="native", noclasses=True)]
)
+
+ def testFormatterLangStr(self):
+ if has_pygments:
+ expected = (
+ '<div class="codehilite"><pre><span></span><code class="language-python">'
+ '<span class="c1"># A Code Comment</span>\n'
+ '</code></pre></div>'
+ )
+ else:
+ expected = (
+ '<pre class="codehilite"><code class="language-python"># A Code Comment\n'
+ '</code></pre>'
+ )
+
+ self.assertMarkdownRenders(
+ '\t:::Python\n'
+ '\t# A Code Comment',
+ expected,
+ extensions=[
+ CodeHiliteExtension(
+ guess_lang=False,
+ pygments_formatter=self.custom_pygments_formatter
+ )
+ ]
+ )
+
+ def testFormatterLangStrGuessLang(self):
+ if has_pygments:
+ expected = (
+ '<div class="codehilite"><pre><span></span>'
+ '<code class="language-js+php"><span class="cp"><?php</span> '
+ '<span class="k">print</span><span class="p">(</span>'
+ '<span class="s2">"Hello World"</span>'
+ '<span class="p">);</span> <span class="cp">?></span>\n'
+ '</code></pre></div>'
+ )
+ else:
+ expected = (
+ '<pre class="codehilite"><code><?php print("Hello World"); ?>\n'
+ '</code></pre>'
+ )
+ # Use PHP as the the starting `<?php` tag ensures an accurate guess.
+ self.assertMarkdownRenders(
+ '\t<?php print("Hello World"); ?>',
+ expected,
+ extensions=[CodeHiliteExtension(pygments_formatter=self.custom_pygments_formatter)]
+ )
+
+ def testFormatterLangStrEmptyLang(self):
+ if has_pygments:
+ expected = (
+ '<div class="codehilite"><pre><span></span>'
+ '<code class="language-text"># A Code Comment\n'
+ '</code></pre></div>'
+ )
+ else:
+ expected = (
+ '<pre class="codehilite"><code># A Code Comment\n'
+ '</code></pre>'
+ )
+ self.assertMarkdownRenders(
+ '\t# A Code Comment',
+ expected,
+ extensions=[
+ CodeHiliteExtension(
+ guess_lang=False,
+ pygments_formatter=self.custom_pygments_formatter,
+ )
+ ]
+ )
from markdown.test_tools import TestCase
import markdown
+import markdown.extensions.codehilite
import os
try:
import pygments # noqa
+ import pygments.formatters # noqa
has_pygments = True
except ImportError:
has_pygments = False
-# The version required by the tests is the version specified and installed in the 'pygments' tox env.
-# In any environment where the PYGMENTS_VERSION environment variable is either not defined or doesn't
-# match the version of Pygments installed, all tests which rely in pygments will be skipped.
+# The version required by the tests is the version specified and installed in the `pygments` tox environment.
+# In any environment where the `PYGMENTS_VERSION` environment variable is either not defined or doesn't
+# match the version of Pygments installed, all tests which rely in Pygments will be skipped.
required_pygments_version = os.environ.get('PYGMENTS_VERSION', '')
extensions=['codehilite', 'fenced_code']
)
- def testFencedMultpleBlocksSameStyle(self):
+ def testFencedMultipleBlocksSameStyle(self):
if has_pygments:
# See also: https://github.com/Python-Markdown/markdown/issues/1240
expected = (
'fenced_code'
]
)
+
+ def testCustomPygmentsFormatter(self):
+ if has_pygments:
+ class CustomFormatter(pygments.formatters.HtmlFormatter):
+ def wrap(self, source, outfile):
+ return self._wrap_div(self._wrap_code(source))
+
+ def _wrap_code(self, source):
+ yield 0, '<code>'
+ for i, t in source:
+ if i == 1:
+ t += '<br>'
+ yield i, t
+ yield 0, '</code>'
+
+ expected = '''
+ <div class="codehilite"><code>hello world
+ <br>hello another world
+ <br></code></div>
+ '''
+
+ else:
+ CustomFormatter = None
+ expected = '''
+ <pre class="codehilite"><code>hello world
+ hello another world
+ </code></pre>
+ '''
+
+ self.assertMarkdownRenders(
+ self.dedent(
+ '''
+ ```
+ hello world
+ hello another world
+ ```
+ '''
+ ),
+ self.dedent(
+ expected
+ ),
+ extensions=[
+ markdown.extensions.codehilite.CodeHiliteExtension(
+ pygments_formatter=CustomFormatter,
+ guess_lang=False,
+ ),
+ 'fenced_code'
+ ]
+ )
+
+ def testPygmentsAddLangClassFormatter(self):
+ if has_pygments:
+ class CustomAddLangHtmlFormatter(pygments.formatters.HtmlFormatter):
+ def __init__(self, lang_str='', **options):
+ super().__init__(**options)
+ self.lang_str = lang_str
+
+ def _wrap_code(self, source):
+ yield 0, f'<code class="{self.lang_str}">'
+ yield from source
+ yield 0, '</code>'
+
+ expected = '''
+ <div class="codehilite"><pre><span></span><code class="language-text">hello world
+ hello another world
+ </code></pre></div>
+ '''
+ else:
+ CustomAddLangHtmlFormatter = None
+ expected = '''
+ <pre class="codehilite"><code class="language-text">hello world
+ hello another world
+ </code></pre>
+ '''
+
+ self.assertMarkdownRenders(
+ self.dedent(
+ '''
+ ```text
+ hello world
+ hello another world
+ ```
+ '''
+ ),
+ self.dedent(
+ expected
+ ),
+ extensions=[
+ markdown.extensions.codehilite.CodeHiliteExtension(
+ guess_lang=False,
+ pygments_formatter=CustomAddLangHtmlFormatter,
+ ),
+ 'fenced_code'
+ ]
+ )
+
+ def testSvgCustomPygmentsFormatter(self):
+ if has_pygments:
+ expected = '''
+ <?xml version="1.0"?>
+ <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
+ <svg xmlns="http://www.w3.org/2000/svg">
+ <g font-family="monospace" font-size="14px">
+ <text x="0" y="14" xml:space="preserve">hello world</text>
+ <text x="0" y="33" xml:space="preserve">hello another world</text>
+ <text x="0" y="52" xml:space="preserve"></text></g></svg>
+ '''
+
+ else:
+ expected = '''
+ <pre class="codehilite"><code>hello world
+ hello another world
+ </code></pre>
+ '''
+
+ self.assertMarkdownRenders(
+ self.dedent(
+ '''
+ ```
+ hello world
+ hello another world
+ ```
+ '''
+ ),
+ self.dedent(
+ expected
+ ),
+ extensions=[
+ markdown.extensions.codehilite.CodeHiliteExtension(
+ pygments_formatter='svg',
+ linenos=False,
+ guess_lang=False,
+ ),
+ 'fenced_code'
+ ]
+ )
+
+ def testInvalidCustomPygmentsFormatter(self):
+ if has_pygments:
+ expected = '''
+ <div class="codehilite"><pre><span></span><code>hello world
+ hello another world
+ </code></pre></div>
+ '''
+
+ else:
+ expected = '''
+ <pre class="codehilite"><code>hello world
+ hello another world
+ </code></pre>
+ '''
+
+ self.assertMarkdownRenders(
+ self.dedent(
+ '''
+ ```
+ hello world
+ hello another world
+ ```
+ '''
+ ),
+ self.dedent(
+ expected
+ ),
+ extensions=[
+ markdown.extensions.codehilite.CodeHiliteExtension(
+ pygments_formatter='invalid',
+ guess_lang=False,
+ ),
+ 'fenced_code'
+ ]
+ )
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
)
def test_backlink_text(self):
- """Test backlink configuration."""
+ """Test back-link configuration."""
self.assertMarkdownRenders(
'paragraph[^1]\n\n[^1]: A Footnote',
'</div>',
extension_configs={'footnotes': {'SEPARATOR': '-'}}
)
+
+ def test_backlink_title(self):
+ """Test back-link title configuration without placeholder."""
+
+ self.assertMarkdownRenders(
+ 'paragraph[^1]\n\n[^1]: A Footnote',
+ '<p>paragraph<sup id="fnref:1"><a class="footnote-ref" href="#fn:1">1</a></sup></p>\n'
+ '<div class="footnote">\n'
+ '<hr />\n'
+ '<ol>\n'
+ '<li id="fn:1">\n'
+ '<p>A Footnote <a class="footnote-backref" href="#fnref:1"'
+ ' title="Jump back to footnote">↩</a></p>\n'
+ '</li>\n'
+ '</ol>\n'
+ '</div>',
+ extension_configs={'footnotes': {'BACKLINK_TITLE': 'Jump back to footnote'}}
+ )
+
+ def test_superscript_text(self):
+ """Test superscript text configuration."""
+
+ self.assertMarkdownRenders(
+ 'paragraph[^1]\n\n[^1]: A Footnote',
+ '<p>paragraph<sup id="fnref:1"><a class="footnote-ref" href="#fn:1">[1]</a></sup></p>\n'
+ '<div class="footnote">\n'
+ '<hr />\n'
+ '<ol>\n'
+ '<li id="fn:1">\n'
+ '<p>A Footnote <a class="footnote-backref" href="#fnref:1"'
+ ' title="Jump back to footnote 1 in the text">↩</a></p>\n'
+ '</li>\n'
+ '</ol>\n'
+ '</div>',
+ extension_configs={'footnotes': {'SUPERSCRIPT_TEXT': '[{}]'}}
+ )
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
def test_stash_to_string(self):
# There should be no known cases where this actually happens so we need to
- # forcefully pass an etree Element to the method to ensure proper behavior.
+ # forcefully pass an `etree` `Element` to the method to ensure proper behavior.
element = Element('div')
element.text = 'Foo bar.'
md = Markdown(extensions=['md_in_html'])
def load_tests(loader, tests, pattern):
- ''' Ensure TestHTMLBlocks doesn't get run twice by excluding it here. '''
+ """ Ensure `TestHTMLBlocks` doesn't get run twice by excluding it here. """
suite = TestSuite()
for test_class in [TestDefaultwMdInHTML, TestMdInHTML, TestMarkdownInHTMLPostProcessor]:
tests = loader.loadTestsFromTestCase(test_class)
--- /dev/null
+# -*- coding: utf-8 -*-
+"""
+Python Markdown
+
+A Python implementation of John Gruber's Markdown.
+
+Documentation: https://python-markdown.github.io/
+GitHub: https://github.com/Python-Markdown/markdown/
+PyPI: https://pypi.org/project/Markdown/
+
+Started by Manfred Stienstra (http://www.dwerg.net/).
+Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
+Currently maintained by Waylan Limberg (https://github.com/waylan),
+Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
+
+Copyright 2007-2022 The Python Markdown Project (v. 1.7 and later)
+Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
+Copyright 2004 Manfred Stienstra (the original version)
+
+License: BSD (see LICENSE.md for details).
+"""
+
+from markdown.test_tools import TestCase
+
+
+class TestSmarty(TestCase):
+
+ default_kwargs = {'extensions': ['smarty']}
+
+ def test_basic(self):
+ self.assertMarkdownRenders(
+ "It's fun. What's fun?",
+ '<p>It’s fun. What’s fun?</p>'
+ )
+ self.assertMarkdownRenders(
+ '"Isn\'t this fun"? --- she said...',
+ '<p>“Isn’t this fun”? — she said…</p>'
+ )
+ self.assertMarkdownRenders(
+ '"\'Quoted\' words in a larger quote."',
+ '<p>“‘Quoted’ words in a larger quote.”</p>'
+ )
+ self.assertMarkdownRenders(
+ '\'Quoted "words" in a larger quote.\'',
+ '<p>‘Quoted “words” in a larger quote.’</p>'
+ )
+ self.assertMarkdownRenders(
+ '"quoted" text and **bold "quoted" text**',
+ '<p>“quoted” text and <strong>bold “quoted” text</strong></p>'
+ )
+ self.assertMarkdownRenders(
+ "'quoted' text and **bold 'quoted' text**",
+ '<p>‘quoted’ text and <strong>bold ‘quoted’ text</strong></p>'
+ )
+ self.assertMarkdownRenders(
+ 'em-dashes (---) and ellipes (...)',
+ '<p>em-dashes (—) and ellipes (…)</p>'
+ )
+ self.assertMarkdownRenders(
+ '"[Link](http://example.com)" --- she said.',
+ '<p>“<a href="http://example.com">Link</a>” — she said.</p>'
+ )
+ self.assertMarkdownRenders(
+ '"Ellipsis within quotes..."',
+ '<p>“Ellipsis within quotes…”</p>'
+ )
+ self.assertMarkdownRenders(
+ "*Custer*'s Last Stand",
+ "<p><em>Custer</em>’s Last Stand</p>"
+ )
+
+ def test_years(self):
+ self.assertMarkdownRenders("1440--80's", '<p>1440–80’s</p>')
+ self.assertMarkdownRenders("1440--'80s", '<p>1440–’80s</p>')
+ self.assertMarkdownRenders("1440---'80s", '<p>1440—’80s</p>')
+ self.assertMarkdownRenders("1960's", '<p>1960’s</p>')
+ self.assertMarkdownRenders("one two '60s", '<p>one two ’60s</p>')
+ self.assertMarkdownRenders("'60s", '<p>’60s</p>')
+
+ def test_wrapping_line(self):
+ text = (
+ "A line that 'wraps' with\n"
+ "*emphasis* at the beginning of the next line."
+ )
+ html = (
+ '<p>A line that ‘wraps’ with\n'
+ '<em>emphasis</em> at the beginning of the next line.</p>'
+ )
+ self.assertMarkdownRenders(text, html)
+
+ def test_escaped(self):
+ self.assertMarkdownRenders(
+ 'Escaped \\-- ndash',
+ '<p>Escaped -- ndash</p>'
+ )
+ self.assertMarkdownRenders(
+ '\\\'Escaped\\\' \\"quotes\\"',
+ '<p>\'Escaped\' "quotes"</p>'
+ )
+ self.assertMarkdownRenders(
+ 'Escaped ellipsis\\...',
+ '<p>Escaped ellipsis...</p>'
+ )
+ self.assertMarkdownRenders(
+ '\'Escaped \\"quotes\\" in real ones\'',
+ '<p>‘Escaped "quotes" in real ones’</p>'
+ )
+ self.assertMarkdownRenders(
+ '\\\'"Real" quotes in escaped ones\\\'',
+ "<p>'“Real” quotes in escaped ones'</p>"
+ )
+
+ def test_escaped_attr(self):
+ self.assertMarkdownRenders(
+ '',
+ '<p><img alt="x"x" src="x" /></p>'
+ )
+
+ def test_code_spans(self):
+ self.assertMarkdownRenders(
+ 'Skip `"code" -- --- \'spans\' ...`.',
+ '<p>Skip <code>"code" -- --- \'spans\' ...</code>.</p>'
+ )
+
+ def test_code_blocks(self):
+ text = (
+ ' Also skip "code" \'blocks\'\n'
+ ' foo -- bar --- baz ...'
+ )
+ html = (
+ '<pre><code>Also skip "code" \'blocks\'\n'
+ 'foo -- bar --- baz ...\n'
+ '</code></pre>'
+ )
+ self.assertMarkdownRenders(text, html)
+
+ def test_horizontal_rule(self):
+ self.assertMarkdownRenders('--- -- ---', '<hr />')
+
+
+class TestSmartyAngledQuotes(TestCase):
+
+ default_kwargs = {
+ 'extensions': ['smarty'],
+ 'extension_configs': {
+ 'smarty': {
+ 'smart_angled_quotes': True,
+ },
+ },
+ }
+
+ def test_angled_quotes(self):
+ self.assertMarkdownRenders(
+ '<<hello>>',
+ '<p>«hello»</p>'
+ )
+ self.assertMarkdownRenders(
+ 'Кавычки-<<ёлочки>>',
+ '<p>Кавычки-«Ñ‘лочки»</p>'
+ )
+ self.assertMarkdownRenders(
+ 'Anführungszeichen->>Chevrons<<',
+ '<p>Anführungszeichen-»Chevrons«</p>'
+ )
+
+
+class TestSmartyCustomSubstitutions(TestCase):
+
+ default_kwargs = {
+ 'extensions': ['smarty'],
+ 'extension_configs': {
+ 'smarty': {
+ 'smart_angled_quotes': True,
+ 'substitutions': {
+ 'ndash': '\u2013',
+ 'mdash': '\u2014',
+ 'ellipsis': '\u2026',
+ 'left-single-quote': '‚', # `sb` is not a typo!
+ 'right-single-quote': '‘',
+ 'left-double-quote': '„',
+ 'right-double-quote': '“',
+ 'left-angle-quote': '[',
+ 'right-angle-quote': ']',
+ },
+ },
+ },
+ }
+
+ def test_custom_substitutions(self):
+ text = (
+ '<< The "Unicode char of the year 2014"\n'
+ "is the 'mdash': ---\n"
+ "Must not be confused with 'ndash' (--) ... >>"
+ )
+ html = (
+ '<p>[ The „Unicode char of the year 2014“\n'
+ 'is the ‚mdash‘: \u2014\n'
+ 'Must not be confused with ‚ndash‘ (\u2013) \u2026 ]</p>'
+ )
+ self.assertMarkdownRenders(text, html)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
"""
from markdown.test_tools import TestCase
+from markdown.extensions.tables import TableExtension
class TestTableBlocks(TestCase):
def test_empty_cells(self):
- """Empty cells (nbsp)."""
+ """Empty cells (`nbsp`)."""
text = """
 | Second Header
),
extensions=['tables']
)
+
+ def test_no_sides(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ First Header | Second Header
+ ------------- | -------------
+ Content Cell | Content Cell
+ Content Cell | Content Cell
+ """
+ ),
+ self.dedent(
+ """
+ <table>
+ <thead>
+ <tr>
+ <th>First Header</th>
+ <th>Second Header</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>Content Cell</td>
+ <td>Content Cell</td>
+ </tr>
+ <tr>
+ <td>Content Cell</td>
+ <td>Content Cell</td>
+ </tr>
+ </tbody>
+ </table>
+ """
+ ),
+ extensions=['tables']
+ )
+
+ def test_both_sides(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ | First Header | Second Header |
+ | ------------- | ------------- |
+ | Content Cell | Content Cell |
+ | Content Cell | Content Cell |
+ """
+ ),
+ self.dedent(
+ """
+ <table>
+ <thead>
+ <tr>
+ <th>First Header</th>
+ <th>Second Header</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>Content Cell</td>
+ <td>Content Cell</td>
+ </tr>
+ <tr>
+ <td>Content Cell</td>
+ <td>Content Cell</td>
+ </tr>
+ </tbody>
+ </table>
+ """
+ ),
+ extensions=['tables']
+ )
+
+ def test_align_columns(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ | Item | Value |
+ | :-------- | -----:|
+ | Computer | $1600 |
+ | Phone | $12 |
+ | Pipe | $1 |
+ """
+ ),
+ self.dedent(
+ """
+ <table>
+ <thead>
+ <tr>
+ <th style="text-align: left;">Item</th>
+ <th style="text-align: right;">Value</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td style="text-align: left;">Computer</td>
+ <td style="text-align: right;">$1600</td>
+ </tr>
+ <tr>
+ <td style="text-align: left;">Phone</td>
+ <td style="text-align: right;">$12</td>
+ </tr>
+ <tr>
+ <td style="text-align: left;">Pipe</td>
+ <td style="text-align: right;">$1</td>
+ </tr>
+ </tbody>
+ </table>
+ """
+ ),
+ extensions=['tables']
+ )
+
+ def test_styles_in_tables(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ | Function name | Description |
+ | ------------- | ------------------------------ |
+ | `help()` | Display the help window. |
+ | `destroy()` | **Destroy your computer!** |
+ """
+ ),
+ self.dedent(
+ """
+ <table>
+ <thead>
+ <tr>
+ <th>Function name</th>
+ <th>Description</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>help()</code></td>
+ <td>Display the help window.</td>
+ </tr>
+ <tr>
+ <td><code>destroy()</code></td>
+ <td><strong>Destroy your computer!</strong></td>
+ </tr>
+ </tbody>
+ </table>
+ """
+ ),
+ extensions=['tables']
+ )
+
+ def test_align_three(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ |foo|bar|baz|
+ |:--|:-:|--:|
+ | | Q | |
+ |W | | W|
+ """
+ ),
+ self.dedent(
+ """
+ <table>
+ <thead>
+ <tr>
+ <th style="text-align: left;">foo</th>
+ <th style="text-align: center;">bar</th>
+ <th style="text-align: right;">baz</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td style="text-align: left;"></td>
+ <td style="text-align: center;">Q</td>
+ <td style="text-align: right;"></td>
+ </tr>
+ <tr>
+ <td style="text-align: left;">W</td>
+ <td style="text-align: center;"></td>
+ <td style="text-align: right;">W</td>
+ </tr>
+ </tbody>
+ </table>
+ """
+ ),
+ extensions=['tables']
+ )
+
+ def test_three_columns(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ foo|bar|baz
+ ---|---|---
+ | Q |
+ W | | W
+ """
+ ),
+ self.dedent(
+ """
+ <table>
+ <thead>
+ <tr>
+ <th>foo</th>
+ <th>bar</th>
+ <th>baz</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td></td>
+ <td>Q</td>
+ <td></td>
+ </tr>
+ <tr>
+ <td>W</td>
+ <td></td>
+ <td>W</td>
+ </tr>
+ </tbody>
+ </table>
+ """
+ ),
+ extensions=['tables']
+ )
+
+ def test_three_spaces_prefix(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ Three spaces in front of a table:
+
+ First Header | Second Header
+ ------------ | -------------
+ Content Cell | Content Cell
+ Content Cell | Content Cell
+
+ | First Header | Second Header |
+ | ------------ | ------------- |
+ | Content Cell | Content Cell |
+ | Content Cell | Content Cell |
+ """),
+ self.dedent(
+ """
+ <p>Three spaces in front of a table:</p>
+ <table>
+ <thead>
+ <tr>
+ <th>First Header</th>
+ <th>Second Header</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>Content Cell</td>
+ <td>Content Cell</td>
+ </tr>
+ <tr>
+ <td>Content Cell</td>
+ <td>Content Cell</td>
+ </tr>
+ </tbody>
+ </table>
+ <table>
+ <thead>
+ <tr>
+ <th>First Header</th>
+ <th>Second Header</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>Content Cell</td>
+ <td>Content Cell</td>
+ </tr>
+ <tr>
+ <td>Content Cell</td>
+ <td>Content Cell</td>
+ </tr>
+ </tbody>
+ </table>
+ """
+ ),
+ extensions=['tables']
+ )
+
+ def test_code_block_table(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ Four spaces is a code block:
+
+ First Header | Second Header
+ ------------ | -------------
+ Content Cell | Content Cell
+ Content Cell | Content Cell
+
+ | First Header | Second Header |
+ | ------------ | ------------- |
+ """),
+ self.dedent(
+ """
+ <p>Four spaces is a code block:</p>
+ <pre><code>First Header | Second Header
+ ------------ | -------------
+ Content Cell | Content Cell
+ Content Cell | Content Cell
+ </code></pre>
+ <table>
+ <thead>
+ <tr>
+ <th>First Header</th>
+ <th>Second Header</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td></td>
+ <td></td>
+ </tr>
+ </tbody>
+ </table>
+ """
+ ),
+ extensions=['tables']
+ )
+
+ def test_inline_code_blocks(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ More inline code block tests
+
+ Column 1 | Column 2 | Column 3
+ ---------|----------|---------
+ word 1 | word 2 | word 3
+ word 1 | `word 2` | word 3
+ word 1 | \\`word 2 | word 3
+ word 1 | `word 2 | word 3
+ word 1 | `word |2` | word 3
+ words |`` some | code `` | more words
+ words |``` some | code ``` | more words
+ words |```` some | code ```` | more words
+ words |`` some ` | ` code `` | more words
+ words |``` some ` | ` code ``` | more words
+ words |```` some ` | ` code ```` | more words
+ """),
+ self.dedent(
+ """
+ <p>More inline code block tests</p>
+ <table>
+ <thead>
+ <tr>
+ <th>Column 1</th>
+ <th>Column 2</th>
+ <th>Column 3</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>word 1</td>
+ <td>word 2</td>
+ <td>word 3</td>
+ </tr>
+ <tr>
+ <td>word 1</td>
+ <td><code>word 2</code></td>
+ <td>word 3</td>
+ </tr>
+ <tr>
+ <td>word 1</td>
+ <td>`word 2</td>
+ <td>word 3</td>
+ </tr>
+ <tr>
+ <td>word 1</td>
+ <td>`word 2</td>
+ <td>word 3</td>
+ </tr>
+ <tr>
+ <td>word 1</td>
+ <td><code>word |2</code></td>
+ <td>word 3</td>
+ </tr>
+ <tr>
+ <td>words</td>
+ <td><code>some | code</code></td>
+ <td>more words</td>
+ </tr>
+ <tr>
+ <td>words</td>
+ <td><code>some | code</code></td>
+ <td>more words</td>
+ </tr>
+ <tr>
+ <td>words</td>
+ <td><code>some | code</code></td>
+ <td>more words</td>
+ </tr>
+ <tr>
+ <td>words</td>
+ <td><code>some ` | ` code</code></td>
+ <td>more words</td>
+ </tr>
+ <tr>
+ <td>words</td>
+ <td><code>some ` | ` code</code></td>
+ <td>more words</td>
+ </tr>
+ <tr>
+ <td>words</td>
+ <td><code>some ` | ` code</code></td>
+ <td>more words</td>
+ </tr>
+ </tbody>
+ </table>
+ """
+ ),
+ extensions=['tables']
+ )
+
+ def test_issue_440(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ A test for issue #440:
+
+ foo | bar
+ --- | ---
+ foo | (`bar`) and `baz`.
+ """),
+ self.dedent(
+ """
+ <p>A test for issue #440:</p>
+ <table>
+ <thead>
+ <tr>
+ <th>foo</th>
+ <th>bar</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>foo</td>
+ <td>(<code>bar</code>) and <code>baz</code>.</td>
+ </tr>
+ </tbody>
+ </table>
+ """
+ ),
+ extensions=['tables']
+ )
+
+ def test_lists_not_tables(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ Lists are not tables
+
+ - this | should | not
+ - be | a | table
+ """),
+ self.dedent(
+ """
+ <p>Lists are not tables</p>
+ <ul>
+ <li>this | should | not</li>
+ <li>be | a | table</li>
+ </ul>
+ """
+ ),
+ extensions=['tables']
+ )
+
+ def test_issue_449(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ r"""
+ Add tests for issue #449
+
+ Odd backticks | Even backticks
+ ------------ | -------------
+ ``[!\"\#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]`` | ``[!\"\#$%&'()*+,\-./:;<=>?@\[\\\]^`_`{|}~]``
+
+ Escapes | More Escapes
+ ------- | ------
+ `` `\`` | `\`
+
+ Only the first backtick can be escaped
+
+ Escaped | Bacticks
+ ------- | ------
+ \`` \` | \`\`
+
+ Test escaped pipes
+
+ Column 1 | Column 2
+ -------- | --------
+ `|` \| | Pipes are okay in code and escaped. \|
+
+ | Column 1 | Column 2 |
+ | -------- | -------- |
+ | row1 | row1 \|
+ | row2 | row2 |
+
+ Test header escapes
+
+ | `` `\`` \| | `\` \|
+ | ---------- | ---- |
+ | row1 | row1 |
+ | row2 | row2 |
+
+ Escaped pipes in format row should not be a table
+
+ | Column1 | Column2 |
+ | ------- \|| ------- |
+ | row1 | row1 |
+ | row2 | row2 |
+
+ Test escaped code in Table
+
+ Should not be code | Should be code
+ ------------------ | --------------
+ \`Not code\` | \\`code`
+ \\\`Not code\\\` | \\\\`code`
+ """),
+ self.dedent(
+ """
+ <p>Add tests for issue #449</p>
+ <table>
+ <thead>
+ <tr>
+ <th>Odd backticks</th>
+ <th>Even backticks</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>[!\\"\\#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~]</code></td>
+ <td><code>[!\\"\\#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^`_`{|}~]</code></td>
+ </tr>
+ </tbody>
+ </table>
+ <table>
+ <thead>
+ <tr>
+ <th>Escapes</th>
+ <th>More Escapes</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>`\\</code></td>
+ <td><code>\\</code></td>
+ </tr>
+ </tbody>
+ </table>
+ <p>Only the first backtick can be escaped</p>
+ <table>
+ <thead>
+ <tr>
+ <th>Escaped</th>
+ <th>Bacticks</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>`<code>\\</code></td>
+ <td>``</td>
+ </tr>
+ </tbody>
+ </table>
+ <p>Test escaped pipes</p>
+ <table>
+ <thead>
+ <tr>
+ <th>Column 1</th>
+ <th>Column 2</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>|</code> |</td>
+ <td>Pipes are okay in code and escaped. |</td>
+ </tr>
+ </tbody>
+ </table>
+ <table>
+ <thead>
+ <tr>
+ <th>Column 1</th>
+ <th>Column 2</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>row1</td>
+ <td>row1 |</td>
+ </tr>
+ <tr>
+ <td>row2</td>
+ <td>row2</td>
+ </tr>
+ </tbody>
+ </table>
+ <p>Test header escapes</p>
+ <table>
+ <thead>
+ <tr>
+ <th><code>`\\</code> |</th>
+ <th><code>\\</code> |</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>row1</td>
+ <td>row1</td>
+ </tr>
+ <tr>
+ <td>row2</td>
+ <td>row2</td>
+ </tr>
+ </tbody>
+ </table>
+ <p>Escaped pipes in format row should not be a table</p>
+ <p>| Column1 | Column2 |
+ | ------- || ------- |
+ | row1 | row1 |
+ | row2 | row2 |</p>
+ <p>Test escaped code in Table</p>
+ <table>
+ <thead>
+ <tr>
+ <th>Should not be code</th>
+ <th>Should be code</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>`Not code`</td>
+ <td>\\<code>code</code></td>
+ </tr>
+ <tr>
+ <td>\\`Not code\\`</td>
+ <td>\\\\<code>code</code></td>
+ </tr>
+ </tbody>
+ </table>
+ """
+ ),
+ extensions=['tables']
+ )
+
+ def test_single_column_tables(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ Single column tables
+
+ | Is a Table |
+ | ---------- |
+
+ | Is a Table
+ | ----------
+
+ Is a Table |
+ ---------- |
+
+ | Is a Table |
+ | ---------- |
+ | row |
+
+ | Is a Table
+ | ----------
+ | row
+
+ Is a Table |
+ ---------- |
+ row |
+
+ | Is not a Table
+ --------------
+ | row
+
+ Is not a Table |
+ --------------
+ row |
+
+ | Is not a Table
+ | --------------
+ row
+
+ Is not a Table |
+ -------------- |
+ row
+ """),
+ self.dedent(
+ """
+ <p>Single column tables</p>
+ <table>
+ <thead>
+ <tr>
+ <th>Is a Table</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td></td>
+ </tr>
+ </tbody>
+ </table>
+ <table>
+ <thead>
+ <tr>
+ <th>Is a Table</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td></td>
+ </tr>
+ </tbody>
+ </table>
+ <table>
+ <thead>
+ <tr>
+ <th>Is a Table</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td></td>
+ </tr>
+ </tbody>
+ </table>
+ <table>
+ <thead>
+ <tr>
+ <th>Is a Table</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>row</td>
+ </tr>
+ </tbody>
+ </table>
+ <table>
+ <thead>
+ <tr>
+ <th>Is a Table</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>row</td>
+ </tr>
+ </tbody>
+ </table>
+ <table>
+ <thead>
+ <tr>
+ <th>Is a Table</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>row</td>
+ </tr>
+ </tbody>
+ </table>
+ <h2>| Is not a Table</h2>
+ <p>| row</p>
+ <h2>Is not a Table |</h2>
+ <p>row |</p>
+ <p>| Is not a Table
+ | --------------
+ row</p>
+ <p>Is not a Table |
+ -------------- |
+ row</p>
+ """
+ ),
+ extensions=['tables']
+ )
+
+ def test_align_columns_legacy(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ | Item | Value |
+ | :-------- | -----:|
+ | Computer | $1600 |
+ | Phone | $12 |
+ | Pipe | $1 |
+ """
+ ),
+ self.dedent(
+ """
+ <table>
+ <thead>
+ <tr>
+ <th align="left">Item</th>
+ <th align="right">Value</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td align="left">Computer</td>
+ <td align="right">$1600</td>
+ </tr>
+ <tr>
+ <td align="left">Phone</td>
+ <td align="right">$12</td>
+ </tr>
+ <tr>
+ <td align="left">Pipe</td>
+ <td align="right">$1</td>
+ </tr>
+ </tbody>
+ </table>
+ """
+ ),
+ extensions=[TableExtension(use_align_attribute=True)]
+ )
+
+ def test_align_three_legacy(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ """
+ |foo|bar|baz|
+ |:--|:-:|--:|
+ | | Q | |
+ |W | | W|
+ """
+ ),
+ self.dedent(
+ """
+ <table>
+ <thead>
+ <tr>
+ <th align="left">foo</th>
+ <th align="center">bar</th>
+ <th align="right">baz</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td align="left"></td>
+ <td align="center">Q</td>
+ <td align="right"></td>
+ </tr>
+ <tr>
+ <td align="left">W</td>
+ <td align="center"></td>
+ <td align="right">W</td>
+ </tr>
+ </tbody>
+ </table>
+ """
+ ),
+ extensions=[TableExtension(use_align_attribute=True)]
+ )
self.assertMarkdownRenders(
r'# escaped\_character',
'<h1 id="escaped_character">escaped_character</h1>',
+ expected_attrs={
+ 'toc': (
+ '<div class="toc">\n'
+ '<ul>\n' # noqa
+ '<li><a href="#escaped_character">escaped_character</a></li>\n' # noqa
+ '</ul>\n' # noqa
+ '</div>\n' # noqa
+ ),
+ 'toc_tokens': [
+ {
+ 'level': 1,
+ 'id': 'escaped_character',
+ 'name': 'escaped_character',
+ 'children': []
+ }
+ ]
+ },
extensions=['toc']
)
'<p>[TOC]<br />\ntext</p>',
extensions=[TocExtension(), Nl2BrExtension()]
)
+
+ def testTOCWithCustomClass(self):
+
+ self.assertMarkdownRenders(
+ self.dedent(
+ '''
+ [TOC]
+ # Header
+ '''
+ ),
+ self.dedent(
+ '''
+ <div class="custom">
+ <ul>
+ <li><a href="#header">Header</a></li>
+ </ul>
+ </div>
+ <h1 id="header">Header</h1>
+ '''
+ ),
+ extensions=[TocExtension(toc_class="custom")]
+ )
+
+ def testTOCWithCustomClasses(self):
+ self.assertMarkdownRenders(
+ self.dedent(
+ '''
+ [TOC]
+ # Header
+ '''
+ ),
+ self.dedent(
+ '''
+ <div class="custom1 custom2">
+ <ul>
+ <li><a href="#header">Header</a></li>
+ </ul>
+ </div>
+ <h1 id="header">Header</h1>
+ '''
+ ),
+ extensions=[TocExtension(toc_class="custom1 custom2")]
+ )
+
+ def testTOCWithEmptyTitleClass(self):
+
+ self.assertMarkdownRenders(
+ self.dedent(
+ '''
+ [TOC]
+ # Header
+ '''
+ ),
+ self.dedent(
+ '''
+ <div class="toc"><span>ToC</span><ul>
+ <li><a href="#header">Header</a></li>
+ </ul>
+ </div>
+ <h1 id="header">Header</h1>
+ '''
+ ),
+ extensions=[TocExtension(title_class="", title='ToC')]
+ )
+
+ def testTOCWithCustomTitleClass(self):
+
+ self.assertMarkdownRenders(
+ self.dedent(
+ '''
+ [TOC]
+ # Header
+ '''
+ ),
+ self.dedent(
+ '''
+ <div class="toc"><span class="tocname">ToC</span><ul>
+ <li><a href="#header">Header</a></li>
+ </ul>
+ </div>
+ <h1 id="header">Header</h1>
+ '''
+ ),
+ extensions=[TocExtension(title_class="tocname", title='ToC')]
+ )
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
'<p>_</p>'
)
+ def test_standalone_asterisks_consecutive(self):
+ self.assertMarkdownRenders(
+ 'Foo * * * *',
+ '<p>Foo * * * *</p>'
+ )
+
+ def test_standalone_understore_consecutive(self):
+ self.assertMarkdownRenders(
+ 'Foo _ _ _ _',
+ '<p>Foo _ _ _ _</p>'
+ )
+
+ def test_standalone_asterisks_pairs(self):
+ self.assertMarkdownRenders(
+ 'Foo ** ** ** **',
+ '<p>Foo ** ** ** **</p>'
+ )
+
+ def test_standalone_understore_pairs(self):
+ self.assertMarkdownRenders(
+ 'Foo __ __ __ __',
+ '<p>Foo __ __ __ __</p>'
+ )
+
+ def test_standalone_asterisks_triples(self):
+ self.assertMarkdownRenders(
+ 'Foo *** *** *** ***',
+ '<p>Foo *** *** *** ***</p>'
+ )
+
+ def test_standalone_understore_triples(self):
+ self.assertMarkdownRenders(
+ 'Foo ___ ___ ___ ___',
+ '<p>Foo ___ ___ ___ ___</p>'
+ )
+
def test_standalone_asterisk_in_text(self):
self.assertMarkdownRenders(
'foo * bar',
'<p>foo\n_ bar _\nbaz</p>'
)
- def test_standalone_asterisks_at_end(self):
+ def test_standalone_underscore_at_begin(self):
+ self.assertMarkdownRenders(
+ '_ foo_ bar',
+ '<p>_ foo_ bar</p>'
+ )
+
+ def test_standalone_asterisk_at_end(self):
self.assertMarkdownRenders(
- 'foo * bar *',
- '<p>foo * bar *</p>'
+ 'foo *bar *',
+ '<p>foo *bar *</p>'
)
def test_standalone_understores_at_begin_end(self):
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
Currently maintained by Waylan Limberg (https://github.com/waylan),
Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
-Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
+Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
Copyright 2004 Manfred Stienstra (the original version)
self.assertMarkdownRenders("<span>e>c</span>", "<p><span>e>c</span></p>")
self.assertMarkdownRenders("<span>e < c</span>", "<p><span>e < c</span></p>")
self.assertMarkdownRenders("<span>e > c</span>", "<p><span>e > c</span></p>")
+
+ def test_inline_html_backslashes(self):
+ self.assertMarkdownRenders('<img src="..\\..\\foo.png">', '<p><img src="..\\..\\foo.png"></p>')
[tox]
-envlist = py36, py37, py38, py39, py310, pypy3, pygments, flake8, checkspelling, pep517check, checklinks
+envlist = py{38, 39, 310, 311, 312}, pypy{38, 39, 310}, pygments, flake8, checkspelling, pep517check, checklinks
isolated_build = True
[testenv]
extras = testing
deps = pytidylib
+allowlist_externals = coverage
commands =
coverage run --source=markdown -m unittest discover {toxinidir}/tests
coverage xml
[testenv:flake8]
deps = flake8
-commands = flake8 {toxinidir}/markdown {toxinidir}/tests {toxinidir}/setup.py
+allowlist_externals = flake8
+commands = flake8 {toxinidir}/markdown {toxinidir}/tests
skip_install = true
[testenv:checkspelling]
-deps =
- mkdocs
- mkdocs_nature
-commands = {toxinidir}/checkspelling.sh
+extras = docs
+deps = pyspelling
+commands =
+ {envpython} -m mkdocs build --strict --config-file {toxinidir}/mkdocs.yml
+ {envpython} -m pyspelling --config {toxinidir}/.pyspelling.yml
[testenv:checklinks]
whitelist_externals = markdown-link-check
[flake8]
max-line-length = 119
-exclude=markdown/pep562.py