### Install mdformat with pip or pipx Source: https://context7.com/hukkin/mdformat/llms.txt Instructions for installing mdformat using pip and pipx. Includes basic installation, recommended CLI usage with pipx, and installation with GitHub Flavored Markdown support. ```bash # Basic installation with CommonMark support pip install mdformat # Or using pipx (recommended for CLI usage) pipx install mdformat # Install with GitHub Flavored Markdown support pipx install mdformat pipx inject mdformat mdformat-gfm ``` -------------------------------- ### mdformat Command-Line Help Source: https://github.com/hukkin/mdformat/blob/master/docs/users/installation_and_usage.md Displays the help message for the mdformat command-line tool, outlining available arguments and options for formatting and checking Markdown files. ```console foo@bar:~$ mdformat --help usage: mdformat [-h] [--check] [--no-validate] [--version] [--number] [--wrap {keep,no,INTEGER}] [--end-of-line {lf,crlf,keep}] [--exclude PATTERN] [--extensions EXTENSION] [--codeformatters LANGUAGE] CommonMark compliant Markdown formatter positional arguments: paths files to format options: -h, --help show this help message and exit --check do not apply changes to files --no-validate do not validate that the rendered HTML is consistent --version show program's version number and exit --number apply consecutive numbering to ordered lists --wrap {keep,no,INTEGER} paragraph word wrap mode (default: keep) --end-of-line {lf,crlf,keep} output file line ending mode (default: lf) --exclude PATTERN exclude files that match the Unix-style glob pattern (multiple allowed) --extensions EXTENSION require and enable an extension plugin (multiple allowed) (use `--no-extensions` to disable) (default: all enabled) --codeformatters LANGUAGE require and enable a code formatter plugin (multiple allowed) (use `--no-codeformatters` to disable) (default: all enabled) ``` -------------------------------- ### Format Markdown File with Options (Python) Source: https://github.com/hukkin/mdformat/blob/master/docs/users/installation_and_usage.md Formats a Markdown file using the mdformat Python API with specified options. This example demonstrates setting 'number' to True and 'wrap' to 60 characters. ```python import mdformat mdformat.file( "FILENAME.md", options={ "number": True, # switch on consecutive numbering of ordered lists "wrap": 60, # set word wrap width to 60 characters } ) ``` -------------------------------- ### Install mdformat with CommonMark Support (Bash) Source: https://github.com/hukkin/mdformat/blob/master/docs/users/installation_and_usage.md Installs the mdformat package with support for CommonMark Markdown specification using pipx. This is the basic installation for standard Markdown formatting. ```bash pipx install mdformat ``` -------------------------------- ### Install mdformat with GFM Support (Bash) Source: https://github.com/hukkin/mdformat/blob/master/docs/users/installation_and_usage.md Installs mdformat and then injects the mdformat-gfm plugin using pipx. This enables support for GitHub Flavored Markdown (GFM) in addition to CommonMark. ```bash pipx install mdformat pipx inject mdformat mdformat-gfm ``` -------------------------------- ### Install Pre-commit Hooks (Bash) Source: https://github.com/hukkin/mdformat/blob/master/docs/contributors/contributing.md Installs the pre-commit hooks for the mdformat project. These hooks help maintain code quality and consistency before committing changes. ```bash pre-commit install ``` -------------------------------- ### Example mdformat TOML Exclude Patterns Source: https://github.com/hukkin/mdformat/blob/master/docs/users/configuration_file.md This TOML snippet illustrates how to define file exclusion patterns in `.mdformat.toml`. It shows examples for excluding single files, directories recursively, specific file types, and more complex pattern matching using glob syntax, which is supported on Python 3.13+. ```toml # .mdformat.toml exclude = [ # exclude a single root level file "CHANGELOG.md", # recursively exclude a root level directory "venv/**", # recursively exclude a directory at any level "**/node_modules/**", # exclude all .txt files "**/*.txt", # exclude all files that are not suffixed .md "**/?", "**/??", "**/???", "**/*[!.]??", "**/*[!m]?", "**/*[!d]", ] ``` -------------------------------- ### Example mdformat TOML Configuration Source: https://github.com/hukkin/mdformat/blob/master/docs/users/configuration_file.md This TOML snippet demonstrates the default configuration values for mdformat. It covers settings for wrapping, numbering, end-of-line characters, validation, extensions, and code formatters. Modifying these values allows for non-default behavior. ```toml # .mdformat.toml # # This file shows the default values and is equivalent to having # no configuration file at all. Change the values for non-default # behavior. # wrap = "keep" # options: {"keep", "no", INTEGER} number = false # options: {false, true} end_of_line = "lf" # options: {"lf", "crlf", "keep"} validate = true # options: {false, true} # extensions = [ # options: a list of enabled extensions (default: all installed are enabled) # "gfm", # "toc", # ] # codeformatters = [ # options: a list of enabled code formatter languages (default: all installed are enabled) # "python", # "json", # ] # Python 3.13+ only: exclude = [] # options: a list of file path pattern strings ``` -------------------------------- ### Format Markdown Files In-Place (Bash) Source: https://github.com/hukkin/mdformat/blob/master/docs/users/installation_and_usage.md Formats specified Markdown files (`README.md`, `CHANGELOG.md`) in place using the mdformat command-line tool. This command modifies the files directly. ```bash mdformat README.md CHANGELOG.md ``` -------------------------------- ### Configure mdformat as Pre-commit Hook (YAML) Source: https://github.com/hukkin/mdformat/blob/master/docs/users/installation_and_usage.md Configures mdformat to be used as a pre-commit hook by adding it to the `.pre-commit-config.yaml` file. This ensures Markdown files are formatted before committing. ```yaml - repo: https://github.com/hukkin/mdformat rev: 1.0.0 # Use the ref you want to point at hooks: - id: mdformat # Optionally add plugins additional_dependencies: - mdformat-gfm - mdformat-black ``` -------------------------------- ### Enable Markdown Extensions with mdformat Source: https://context7.com/hukkin/mdformat/llms.txt Shows how to use mdformat to enable specific Markdown syntax extensions like tables and footnotes. Requires relevant plugins (e.g., 'mdformat-gfm') to be installed. It processes Markdown content and applies the specified extensions. ```python import mdformat # Requires mdformat-gfm plugin to be installed markdown_with_table = """ | Header 1 | Header 2 | |----------|----------| | Cell 1 | Cell 2 | """ # Enable GFM tables extension formatted = mdformat.text(markdown_with_table, extensions={"tables"}) print(formatted) # Multiple extensions formatted = mdformat.text( content, extensions={"tables", "footnote", "frontmatter"} ) ``` -------------------------------- ### Check Markdown File Formatting (Bash) Source: https://github.com/hukkin/mdformat/blob/master/docs/users/installation_and_usage.md Checks the formatting of specified Markdown files (`README.md`, `CHANGELOG.md`) without applying any changes. If files are not properly formatted, the command exits with a non-zero status code. ```bash mdformat --check README.md CHANGELOG.md ``` -------------------------------- ### Integrate mdformat with Pre-commit Hook Source: https://context7.com/hukkin/mdformat/llms.txt Provides configuration for integrating mdformat as a pre-commit hook. This ensures Markdown files are automatically formatted before committing. It includes steps for configuring `.pre-commit-config.yaml`, installing the hook, and running it manually or on specific files. ```yaml # .pre-commit-config.yaml repos: - repo: https://github.com/hukkin/mdformat rev: 1.0.0 # Use the version you want hooks: - id: mdformat # Optionally add plugins additional_dependencies: - mdformat-gfm - mdformat-black - mdformat-frontmatter ``` ```bash # Install the hook pre-commit install # Run manually on all files pre-commit run mdformat --all-files # Run on specific files pre-commit run mdformat --files README.md docs/*.md ``` -------------------------------- ### Format Python Code Blocks with mdformat-black Source: https://context7.com/hukkin/mdformat/llms.txt Demonstrates how to use mdformat to automatically format Python code blocks within Markdown files. Requires the 'mdformat-black' plugin to be installed. It takes unformatted Markdown as input and returns the formatted version. ```python import mdformat # Requires mdformat-black plugin to be installed unformatted = """```python '''black converts quotes''' x=1+2 ``` " # Enable Python code formatting formatted = mdformat.text(unformatted, codeformatters={"python"}) print(formatted) # Output: # ```python # """black converts quotes""" # x = 1 + 2 # ``` # Multiple code formatters markdown_with_code = """ ```python x=1 ``` ```json {"key":"value"} ``` " # Requires mdformat-black and mdformat-config plugins formatted = mdformat.text( markdown_with_code, codeformatters={"python", "json"} ) ``` -------------------------------- ### Format Markdown Text (Python) Source: https://github.com/hukkin/mdformat/blob/master/docs/users/installation_and_usage.md Formats a given Markdown string using the mdformat Python API. It takes an unformatted string as input and returns a formatted string. ```python import mdformat unformatted = "\n\n# A header\n\n" formatted = mdformat.text(unformatted) assert formatted == "# A header\n" ``` -------------------------------- ### Format Markdown from Standard Input (Bash) Source: https://github.com/hukkin/mdformat/blob/master/docs/users/installation_and_usage.md Reads Markdown content from standard input until EOF, formats it, and writes the result to standard output. This is useful for piping Markdown content to mdformat. ```bash mdformat - ``` -------------------------------- ### Format Markdown Files Recursively (Bash) Source: https://github.com/hukkin/mdformat/blob/master/docs/users/installation_and_usage.md Formats all `.md` files in the current working directory and its subdirectories recursively. The mdformat command is applied to every Markdown file found. ```bash mdformat . ``` -------------------------------- ### Format Markdown File In-Place (Python) Source: https://github.com/hukkin/mdformat/blob/master/docs/users/installation_and_usage.md Formats a Markdown file in place using the mdformat Python API. It accepts either a string path or a pathlib.Path object for the file to be formatted. ```python import mdformat import pathlib # Input filepath as a string... mdformat.file("README.md") # ...or a pathlib.Path object filepath = pathlib.Path("README.md") mdformat.file(filepath) ``` -------------------------------- ### Format Python Code Blocks with Mdformat API Source: https://github.com/hukkin/mdformat/blob/master/docs/users/plugins.md Demonstrates how to use the mdformat Python API to format Python code blocks within Markdown. This requires the `mdformat-black` plugin to be installed and the 'python' codeformatter to be explicitly enabled. ```python import mdformat unformatted = "```python\n'''black converts quotes'''\n```\n" # Pass in `codeformatters` here! It is an iterable of coding languages # that should be formatted formatted = mdformat.text(unformatted, codeformatters={"python"}) assert formatted == '```python\n"""black converts quotes"""\n```\n' ``` -------------------------------- ### Enable Markdown Parser Extensions with Mdformat API Source: https://github.com/hukkin/mdformat/blob/master/docs/users/plugins.md Shows how to use the mdformat Python API to enable Markdown parser extensions, such as tables. This requires the relevant plugin to be installed and the extension to be explicitly enabled. ```python import mdformat unformatted = "content...\n" # Pass in `extensions` here! It is an iterable of extensions that should be loaded formatted = mdformat.text(unformatted, extensions={"tables"}) ``` -------------------------------- ### Define Parser Extension Entry Point (Python/Setuptools) Source: https://github.com/hukkin/mdformat/blob/master/docs/contributors/contributing.md Configures the entry point for a mdformat parser extension plugin using setuptools in setup.py. This makes the extension discoverable by mdformat. ```python import setuptools setuptools.setup( # other arguments here... entry_points={ "mdformat.parser_extension": ["myextension = my_package:ext_module_or_class"] } ) ``` -------------------------------- ### Define Code Formatter Entry Point (Python/Setuptools) Source: https://github.com/hukkin/mdformat/blob/master/docs/contributors/contributing.md Configures the entry point for a mdformat code formatter plugin using setuptools in setup.py. This makes the formatter discoverable by mdformat. ```python import setuptools setuptools.setup( # other arguments here... entry_points={ "mdformat.codeformatter": ["python = my_package.some_module:format_python"] } ) ``` -------------------------------- ### mdformat CLI options for formatting Source: https://context7.com/hukkin/mdformat/llms.txt Illustrates various command-line options for mdformat, including showing help, numbering lists, setting word wrap, line endings, excluding files, skipping validation, and enabling extensions/code formatters. ```bash # Show help with all options mdformat --help # Apply consecutive numbering to ordered lists mdformat --number document.md # Set word wrap width (default: keep original wrapping) mdformat --wrap 80 document.md # Remove word wrapping mdformat --wrap no document.md # Set line ending mode (lf, crlf, or keep) mdformat --end-of-line crlf document.md # Exclude files matching glob pattern (Python 3.13+ only) mdformat --exclude "*.generated.md" --exclude "vendor/**" . # Skip AST validation check mdformat --no-validate document.md # Enable specific extensions only mdformat --extensions tables --extensions footnote document.md # Enable specific code formatters only mdformat --codeformatters python --codeformatters json document.md ``` -------------------------------- ### Format Markdown files using the CLI Source: https://context7.com/hukkin/mdformat/llms.txt Demonstrates how to use the mdformat command-line tool to format Markdown files. Covers formatting specific files, all files in a directory, and piping input/output. ```bash # Format specific files mdformat README.md CHANGELOG.md # Format all .md files in current directory recursively mdformat . # Format from standard input and write to standard output echo "# Hello World" | mdformat - # Output: # Hello World ``` -------------------------------- ### mdformat CLI Help (Console) Source: https://github.com/hukkin/mdformat/blob/master/README.md Displays the help message for the mdformat command-line interface, outlining available commands and options. ```console foo@bar:~$ mdformat --help usage: mdformat [-h] [--check] [--no-validate] [--version] [--number] [--wrap {keep,no,INTEGER}] [--end-of-line {lf,crlf,keep}] [--exclude PATTERN] [--extensions EXTENSION] [--codeformatters LANGUAGE] [paths ...] CommonMark compliant Markdown formatter positional arguments: paths files to format options: -h, --help show this help message and exit --check do not apply changes to files --no-validate do not validate that the rendered HTML is consistent --version show program's version number and exit --number apply consecutive numbering to ordered lists --wrap {keep,no,INTEGER} paragraph word wrap mode (default: keep) --end-of-line {lf,crlf,keep} output file line ending mode (default: lf) --exclude PATTERN exclude files that match the Unix-style glob pattern (multiple allowed) --extensions EXTENSION require and enable an extension plugin (multiple allowed) (use `--no-extensions` to disable) (default: all enabled) --codeformatters LANGUAGE require and enable a code formatter plugin (multiple allowed) (use `--no-codeformatters` to disable) (default: all enabled) ``` -------------------------------- ### Define Code Formatter Entry Point (TOML/PEP 621) Source: https://github.com/hukkin/mdformat/blob/master/docs/contributors/contributing.md Configures the entry point for a mdformat code formatter plugin using a PEP 621 compliant pyproject.toml file. This is an alternative to using setup.py. ```toml # other config here... [project.entry-points."mdformat.codeformatter"] "python" = "my_package.some_module:format_python" ``` -------------------------------- ### Define Parser Extension Entry Point (TOML/Poetry) Source: https://github.com/hukkin/mdformat/blob/master/docs/contributors/contributing.md Configures the entry point for a mdformat parser extension plugin using Poetry in pyproject.toml. This is a specific configuration for Poetry users. ```toml # Poetry specific: [tool.poetry.plugins."mdformat.parser_extension"] "myextension" = "my_package:ext_module_or_class" ``` -------------------------------- ### Check Markdown file formatting with CLI Source: https://context7.com/hukkin/mdformat/llms.txt Shows how to use the mdformat CLI to check if Markdown files are properly formatted without applying changes. This is useful for CI pipelines. ```bash # Returns non-zero exit code if files are not properly formatted mdformat --check README.md CHANGELOG.md # Use in CI pipelines mdformat --check . || echo "Markdown files need formatting" ``` -------------------------------- ### Configure mdformat with TOML Source: https://context7.com/hukkin/mdformat/llms.txt Illustrates how to configure mdformat using a `.mdformat.toml` file. This file allows setting options like word wrap mode, list numbering, line endings, and enabling specific extensions or code formatters. CLI arguments take precedence over configuration file settings. ```toml # .mdformat.toml # Word wrap mode: "keep", "no", or an integer width wrap = "keep" # Use consecutive numbering for ordered lists number = false # Line ending mode: "lf", "crlf", or "keep" end_of_line = "lf" # Validate that HTML output is consistent after formatting validate = true # Enable only specific extensions (default: all installed are enabled) extensions = [ "tables", "footnote", ] # Enable only specific code formatters (default: all installed are enabled) codeformatters = [ "python", "json", ] # Exclude patterns (Python 3.13+ only) exclude = [ "CHANGELOG.md", "venv/**", "**/node_modules/**", "**/*.generated.md", ] # Plugin-specific configuration [plugin.gfm] # Plugin-specific options go here ``` -------------------------------- ### Define Parser Extension Entry Point (TOML/PEP 621) Source: https://github.com/hukkin/mdformat/blob/master/docs/contributors/contributing.md Configures the entry point for a mdformat parser extension plugin using a PEP 621 compliant pyproject.toml file. This works with build backends like Flit. ```toml # or PEP 621 compliant (works with Flit): [project.entry-points."mdformat.parser_extension"] "myextension" = "my_package:ext_module_or_class" ``` -------------------------------- ### Develop a Custom mdformat Parser Extension Plugin Source: https://context7.com/hukkin/mdformat/llms.txt Explains how to create a parser extension plugin for mdformat to support custom Markdown syntax. This requires implementing the `ParserExtensionInterface` and providing functions to update the Markdown parser (`update_mdit`) and render custom nodes (`render_my_syntax`). Entry points are configured in `pyproject.toml`. ```python # my_extension/__init__.py from collections.abc import Mapping from markdown_it import MarkdownIt from mdformat.renderer import RenderContext, RenderTreeNode from mdformat.renderer.typing import Render def update_mdit(mdit: MarkdownIt) -> None: """Extend the Markdown parser with custom syntax.""" # Add your markdown-it-py plugin # mdit.use(my_custom_plugin) pass def render_my_syntax(node: RenderTreeNode, context: RenderContext) -> str: """Render the custom syntax node.""" # Return the Markdown representation return f":::my-syntax\n{node.content}\n:::\n" # Mapping of node types to render functions RENDERERS: Mapping[str, Render] = { "my_syntax": render_my_syntax, } # Optional: Set to True if formatting changes the AST CHANGES_AST: bool = False # pyproject.toml entry point configuration # [project.entry-points."mdformat.parser_extension"] # my_extension = "my_extension:ext_module" ``` -------------------------------- ### Format Markdown file in place with Python API Source: https://context7.com/hukkin/mdformat/llms.txt Explains how to use the `mdformat.file()` Python function to format Markdown files directly. Covers formatting by string path or `pathlib.Path`, applying options, enabling extensions, and error handling for non-existent files or symlinks. ```python import mdformat from pathlib import Path # Format a file using string path mdformat.file("README.md") # Format a file using pathlib.Path filepath = Path("docs/guide.md") mdformat.file(filepath) # Format with options mdformat.file( "document.md", options={ "number": True, # Consecutive list numbering "wrap": 80, # Word wrap at 80 characters "end_of_line": "lf", # Use LF line endings } ) # Format with extensions enabled (requires plugins to be installed) mdformat.file( "README.md", extensions={"tables", "footnote"}, # Enable specific parser extensions codeformatters={"python", "json"}, # Enable specific code formatters ) # Error handling try: mdformat.file("nonexistent.md") except ValueError as e: print(f"Error: {e}") # Output: Error: Cannot format "nonexistent.md". It is not a file. try: mdformat.file("symlink.md") except ValueError as e: print(f"Error: {e}") # Output: Error: Cannot format "symlink.md". It is a symlink. ``` -------------------------------- ### Format Markdown string with Python API Source: https://context7.com/hukkin/mdformat/llms.txt Demonstrates the `mdformat.text()` function in Python for formatting Markdown strings. Shows basic formatting, applying options like list numbering and word wrapping. ```python import mdformat # Basic formatting unformatted = "\n\n# A header\n\n" formatted = mdformat.text(unformatted) print(formatted) # Output: "# A header\n" # Format with options messy_markdown = """ 1. First item 2. Second item 3. Third item """ # Apply consecutive numbering to ordered lists formatted = mdformat.text(messy_markdown, options={"number": True}) print(formatted) # Output: # 1. First item # 2. Second item # 3. Third item # Set word wrap width long_paragraph = "This is a very long paragraph that should be wrapped at a specific width for better readability in the source file." formatted = mdformat.text(long_paragraph, options={"wrap": 40}) print(formatted) # Output: wraps text at 40 characters # Remove word wrapping entirely formatted = mdformat.text(long_paragraph, options={"wrap": "no"}) print(formatted) # Output: all on one line ``` -------------------------------- ### Test Pre-commit Hook (Bash) Source: https://github.com/hukkin/mdformat/blob/master/docs/contributors/contributing.md Tests the pre-commit hook against a specific file, in this case, README.md. This command verifies that the hook correctly processes the specified file. ```bash pre-commit try-repo . mdformat --files README.md ``` -------------------------------- ### Create a Custom mdformat Code Formatter Plugin Source: https://context7.com/hukkin/mdformat/llms.txt Details on developing a custom code formatter plugin for mdformat. This involves creating a Python function to format code blocks for a specific language (e.g., 'mylang') and configuring entry points in `pyproject.toml`. The formatter function receives code and info string, returning the formatted code. ```python # my_plugin/formatter.py def format_mylang(code: str, info_string: str) -> str: """Format code block content. Args: code: The unformatted code block content info_string: The full info string (e.g., "python title=example.py") Returns: Formatted code (must end with newline if non-empty) """ # Your formatting logic here formatted = code.strip().upper() # Example: uppercase the code return formatted + "\n" if formatted else "" # pyproject.toml entry point configuration # [project.entry-points."mdformat.codeformatter"] # mylang = "my_plugin.formatter:format_mylang" ``` -------------------------------- ### Run Tests with Tox (Bash) Source: https://github.com/hukkin/mdformat/blob/master/docs/contributors/contributing.md Executes the test suite for mdformat using Tox. This command ensures that all tests pass after making code changes. ```bash tox ``` -------------------------------- ### Custom Heading Renderer in Python Source: https://context7.com/hukkin/mdformat/llms.txt Defines a custom renderer for heading nodes in Markdown using mdformat's RenderContext and RenderTreeNode. It demonstrates accessing formatting options, handling wrapping logic, using indentation context, and accessing environment variables. ```python from mdformat.renderer import RenderContext, RenderTreeNode, DEFAULT_RENDERERS def custom_heading_renderer(node: RenderTreeNode, context: RenderContext) -> str: """Custom renderer for heading nodes.""" # Render children using the default inline renderer text = "" for child in node.children: text += child.render(context) # Access formatting options wrap_mode = context.options.get("mdformat", {}).get("wrap", "keep") # Check if word wrapping is enabled if context.do_wrap: # Handle wrapping logic pass # Use indentation context for nested content with context.indented(2): # Content rendered here will track 2 additional indent characters nested_content = " " + text # Get a context with default renderer for specific syntax default_context = context.with_default_renderer_for("paragraph", "text") # Access environment variables used_refs = context.env["used_refs"] indent_width = context.env["indent_width"] return f"# {text}" ``` -------------------------------- ### Markdown Hard Line Break Conversion Source: https://github.com/hukkin/mdformat/blob/master/docs/users/style.md This snippet demonstrates the conversion of hard line breaks in Markdown. Mdformat replaces trailing spaces before a line ending with a backslash escape character to ensure consistent rendering of hard line breaks. ```markdown Input: ```markdown Hard line break is here: Can you see it? ``` Output: ```markdown Hard line break is here:\ Can you see it? ``` ``` -------------------------------- ### Parser Extension Interface Definition (Python) Source: https://github.com/hukkin/mdformat/blob/master/docs/contributors/contributing.md Defines the interface for a mdformat parser extension plugin. It includes functions to update the Markdown parser and provide custom renderers. ```python from collections.abc import Mapping from markdown_it import MarkdownIt from mdformat.renderer.typing import Render def update_mdit(mdit: MarkdownIt) -> None: """Update the parser, e.g. by adding a plugin: `mdit.use(myplugin)`""" # A mapping from `RenderTreeNode.type` value to a `Render` function that can # render the given `RenderTreeNode` type. These functions override the default # `Render` funcs defined in `mdformat.renderer.DEFAULT_RENDERERS`. RENDERERS: Mapping[str, Render] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.