snippet-fmt¶
Format and validate code snippets in reStructuredText files.
Installation¶
python3 -m pip install snippet-fmt --user
python3 -m pip install git+https://github.com/python-formate/snippet-fmt@master --user
Usage¶
Command Line¶
Reformat code snippets in the given reStructuredText files.
snippet-fmt [OPTIONS] [FILENAME]...
Options
-
-c
,
--config-file
<config_file>
¶ The path to the TOML configuration file to use.
- Default
pyproject.toml
-
-e
,
--exclude
<PATTERN>
¶ Patterns for files to exclude from formatting.
-
-v
,
--verbose
¶
Show verbose output.
-
--colour
,
--no-colour
¶
Whether to use coloured output.
-
-T
,
--traceback
¶
Show the complete traceback on error.
-
--diff
¶
Show a diff of changes made
Arguments
-
FILENAME
¶
Optional argument(s). Default
None
As a pre-commit
hook¶
snippet-fmt
can also be used as a pre-commit hook.
To do so, add the following to your
.pre-commit-config.yaml file:
- repo: https://github.com/python-formate/snippet-fmt
rev: 0.1.5
hooks:
- id: snippet-fmt
args:
- --verbose
The args
option can be used to provide the command line arguments shown above.
By default snippet-fmt
is run with --verbose --diff
Configuration¶
snippet-fmt
is configured using the pyproject.toml
file in the root of your project
(alongside setup.py
, tox.ini
etc.).
The file uses the TOML syntax,
with the configuration in the [tool.snippet-fmt]
table.
The table can contain two keys: languages
and directives
Alternatively, the -c / --config-file
option can be used to point to a different TOML file.
The layout is the same except the table [snippet-fmt]
rather than [tool.snippet.fmt]
.
-
languages
¶ This is a table of tables giving languages to check and reformat.
These correspond to the value after
.. code-block::
, preserving case.For example, the following codeblock has a value of
'TOML'
:.. code-block:: TOML key = "value"
Each language has a corresponding check / reformat function, which is determined from the lowercased form of the language name. This allows certain code blocks in a language to be excluded from formatting by using a different case, such as using
TOML
for most code blocks andtoml
for ones which shouldn’t be reformatted.The currently supported languages (matched case insensitively) are:
JSON
INI
TOML
Python / Python3
Each sub table contains options specific to that language (and capitalisation). The exact options vary, but each has a
reformat
option which defaults toFalse
. If set toTrue
the code snippets in that language will be reformatted, otherwise they will only be syntax checked.By default all languages are enabled for checks only.
-
directives
¶ The directive types to reformat, such as
'code-block'
for.. code-block::
.The values are case sensitive.
Defaults to
['code', 'code-block', 'sourcecode']
.
Supported Languages¶
The following languages are supported by snippet-fmt
:
Python / Python3¶
Reformatting Python files with formate.
Options
JSON¶
Syntax checking and reformatting of JSON files, using Python’s json
module.
Options
-
json.
reformat
¶ - Type: BooleanDefault: False
If set to
true
the code blocks matching this language and capitalisation will be reformatted, otherwise they will only be syntax checked.
-
json.
ensure_ascii
¶ - Type: BooleanDefault: false
If
true
, the output is guaranteed to have all incoming non-ASCII characters escaped. Iffalse
(the default), these characters will be output as-is.
-
json.
allow_nan
¶ - Type: BooleanDefault: true
If
true
(the default), thenNaN
,Infinity
, and-Infinity
will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise an error will be raised when attepting to reformat files containing such floats.Note
JSON snippets containing
NaN
etc. when this option isfalse
andreformat
is alsofalse
will pass, as this check only takes place durinh reformatting.
-
json.
indent
¶ -
If
indent
is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or “” will only insert newlines. If not specified a compact representation will be used. Using a positive integer indent indents that many spaces per level. If indent is a string (such as “t”), that string is used to indent each level.
-
json.
separators
¶ -
A 2-element array of
[item_separator, key_separator]
. The default is(', ', ': ')
ifindent
is unspecified and(',', ': ')
otherwise. To get the most compact JSON representation, you should specify(',', ':')
to eliminate whitespace.
Example¶
[tool.snippet-fmt]
directives = [ "code", "code-block", "sourcecode",]
[tool.snippet-fmt.languages.python]
reformat = true
config-file = "pyproject.toml"
[tool.snippet-fmt.languages.TOML]
reformat = true
[tool.snippet-fmt.languages.toml]
[tool.snippet-fmt.languages.ini]
This will:
look at
.. code::
,.. code-block::
and.. sourcecode::
directives forpython
,TOML
,toml
, andini
.Code blocks marked
python
andTOML
will be reformatted.Code blocks marked
toml
andini
will only be checked for valid syntax.formate is configured to take its configuration from
pyproject.toml
.
Changelog¶
v0.1.4¶
Fixed typo in the regular expression preventing single line code blocks from matching.
v0.1.3¶
Ensure indentation is preserved with nested directives.
v0.1.2¶
Correctly handle indentation containing mixed tabs and spaces.
v0.1.1¶
Corrected filetypes in .pre-commit-hooks.yaml
.
v0.1.0¶
Initial Release
Downloading source code¶
The snippet-fmt
source code is available on GitHub,
and can be accessed from the following URL: https://github.com/python-formate/snippet-fmt
If you have git
installed, you can clone the repository with the following command:
git clone https://github.com/python-formate/snippet-fmt
Cloning into 'snippet-fmt'...
remote: Enumerating objects: 47, done.
remote: Counting objects: 100% (47/47), done.
remote: Compressing objects: 100% (41/41), done.
remote: Total 173 (delta 16), reused 17 (delta 6), pack-reused 126
Receiving objects: 100% (173/173), 126.56 KiB | 678.00 KiB/s, done.
Resolving deltas: 100% (66/66), done.

Downloading a ‘zip’ file of the source code¶
Building from source¶
The recommended way to build snippet-fmt
is to use tox:
tox -e build
The source and wheel distributions will be in the directory dist
.
If you wish, you may also use pep517.build or another PEP 517-compatible build tool.
License¶
snippet-fmt
is licensed under the MIT License
A short and simple permissive license with conditions only requiring preservation of copyright and license notices. Licensed works, modifications, and larger works may be distributed under different terms and without source code.
Permissions | Conditions | Limitations |
---|---|---|
|
|
Copyright (c) 2021 Dominic Davis-Foster
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.
snippet_fmt
¶
Format and validate code snippets in reStructuredText files.
Classes:
|
Represents an exception raised when parsing and reformatting a code block. |
|
Reformat code snippets in a reStructuredText file. |
Functions:
|
Reformat the given reStructuredText file, and show the diff if changes were made. |
-
namedtuple
CodeBlockError
(offset, exc)[source]¶ Bases:
NamedTuple
Represents an exception raised when parsing and reformatting a code block.
- Fields
-
__repr__
()¶ Return a nicely formatted representation string
-
class
RSTReformatter
(filename, config)[source]¶ Bases:
object
Reformat code snippets in a reStructuredText file.
- Parameters
filename (
Union
[str
,Path
,PathLike
]) – The filename to reformat.config (
SnippetFmtConfigDict
) – Thesnippet_fmt
configuration, parsed from a TOML file (or similar).
Attributes:
The
formate
configuration, parsed from a TOML file (or similar).The filename being reformatted, as a POSIX-style path.
The filename being reformatted.
Methods:
get_diff
()Returns the diff between the original and reformatted file content.
Load custom formatters defined via entry points.
process_match
(match)Process a
re.Match
for a single code block.run
()Run the reformatter.
to_file
()Write the reformatted source to the original file.
Return the reformatted file as a string.
-
config
¶ Type:
SnippetFmtConfigDict
The
formate
configuration, parsed from a TOML file (or similar).
snippet_fmt.config
¶
Read and parse snippet-fmt
configuration.
Classes:
|
Functions:
|
Load the |
-
typeddict
SnippetFmtConfigDict
[source]¶ Bases:
TypedDict
typing.TypedDict
representing the configuration mapping parsed fromformate.toml
or similar.- Required Keys
languages (
Dict
[str
,Dict
[str
,Any
]]) – The languages to reformat. The keys correspond to the value after.. code-block::
, including matching case. The values arekey: value
mappings giving language-specific options. The exact options vary, but each has areformat
option which defaults toFalse
. If set toTrue
the code snippets in that language will be reformatted, otherwise they will only be syntax checked. For example, the following code block has a value of'TOML'
: .. code-block:: rst .. code-block:: TOML key = “value” Different capitalisation (e.g.JSON
vsjson
) can be used to apply different settings to different groups of code blocks. For example,JSON
code blocks could have and indent of 2, butjson
blocks have no indentation.directives (
List
[str
]) – The directive types to reformat, such as'code-block'
for.. code-block::
. The values are case sensitive.
snippet_fmt.formatters
¶
Formatters and syntax checkers.
Classes:
|
Functions:
|
Check the syntax of, and reformat, the given INI configuration. |
|
Check the syntax of, and reformat, the given JSON source. |
|
Check the syntax of, and reformat, the given Python code. |
|
Check the syntax of, and reformat, the given TOML configuration. |
|
A no-op formatter. |
-
protocol
Formatter
[source]¶ Bases:
Protocol
typing.Protocol
for formatter functions.Classes that implement this protocol must have the following methods / attributes:
View the Function Index or browse the Source Code.