You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Apply ruff formatting to markdown code blocks #3792
Reacted by Janosh Riebesell, Pavel Perestoronin, T-256, Jan Katins, mo, Edgar Ramírez Mondragón, Lars Bilke, Yolan Honoré-Rougé, gebbissimo, Niccolò Mineo and 51 more
I'm interested in trying to implement this. Looking at the projects listed above, it seems like code blocks are determined via Regex. Do we want to copy that approach or use a more robust Markdown parser (pulldown-cmark seems like a popular one)?
Using a markdown parser makes sense from my view. It may be worth to also consider tree-sitter because it supports many languages.
The part that's unclear to me how we want to solve it in the short term is the mapping of column and line numbers in the Messageemitters. Ruff supports Jupyter-notebooks today, but the line-mapping is somewhat "hacked-in" to make it work, and I'm a bit reluctant to add more exceptions to the line-number mapping.
I assume a similar mapping will be necessary for Markdown files because we only pass the code block's source to Ruff, but we should show users the absolute line number from the start of the Markdown document.
Long-term
Long-term, we'll need to support the following two features.
Multi-language support
Ruff should support linting different file types. For example, Ruff should be able to lint SQL, python, and Markdown files. The filetype decides which specific linter Ruff uses to lint the file. This includes that the LSP is in sync with the file-types supported by the CLI and what extensions map to which languages. Rome supports this today.
Embedded Languages
The idea is that a document written in one language can contain code written in another language. Examples are:
Code blocks in markdown documents
SQL in Python code
Python code in Jupyter Notebooks
The markdown file handler would recognize code blocks and delegate to Ruff to decide how to parse, lint, and format the code block's content. Ruff's infrastructure would correctly map the line-numbers between the "virtual" documents and the "physical" documents on disk.
Yup, agree with all of your points @MichaReiser. As part of the design phase I've been thinking about how to generalize to different filetypes. It's an interesting problem - I will take a look at Treesitter parsers as well. Going down that route, we could support different languages relatively easily. I am going to submit PRs for this incrementally so that we can iterate over the design. The first one will be a parser that pulls code blocks out of Markdown - I'm leaning towards using Treesitter since that architecture could make it easier to provide "plugins" for other languages in the future.
As far as the line mappings, I was planning on making a generic LineMap struct (or something along those lines) which would contain line numbers mapped to their offset in the containing document. That struct could then be reused for embedded languages, like you mentioned, mapping relative line numbers in the chunk of interest to the absolute line number of the document. It should provide a flexible way to treat code blocks differently, regardless of if it's an embedded language, a markdown code block, a Jupyter cell, etc.
I'll have to look into Messages and how they work before finalizing the code though. I've been reading through the Jupyter implementation as part of this.
As far as the line mappings, I was planning on making a generic LineMap struct (or something along those lines) which would contain line numbers mapped to their offset in the containing document.
Mapping line numbers should suffice for markdown documents but wouldn't be sufficient for e.g. SQL in python. I think it may actually be sufficient to simply add the byte offset of the markdown block to the range of every message/diagnostic.
Yup, that's basically what I'm doing - adding a document_offset field to Messages and Diagnostics.
As far as the SQL in Python example, I was thinking the approach could work because the document_offset would be where the SQL code starts relative to the Python file. Line 1 of the SQL code could be on line 50 of the overarching .py file, so the document_offset for all diagnostics/messages in that block would be 50. Do you think there are flaws in that approach?
E: sorry, not mapping line numbers. Mapping byte offsets between SQL/Python lines. I still need to figure out a concrete design though, if you couldn't tell 😅
Going with a treesitter integration requires installing the treesitter grammar for the language in question. While we could gate this behind a workspace feature flag, I'd like some other folk's thoughts on it. I don't want to needlessly increase the binary size. I need to figure out how it all works to give exact an estimate of the increase, though.
Advantage of pulldown-cmark as mentioned above is it's quite fast and won't affect the binary size. Disadvantage is that it obviously can't be used for anything except Markdown.
Yup, that's basically what I'm doing - adding a document_offset field to Messages and Diagnostics.
Which use cases require a diagnostic or message to know its document offset? Would it be sufficient to mutate the diagnostic.range or message.range directly by adding the offset? I'm asking because increasing the size of Message and Diagnostic decrease performance because:
More data that must be written to and read from the cache
Overall more data to write when creating/copying diagnostics and read when generating the output (even for diagnostics not using embedded languages)
Advantage of pulldown-cmark as mentioned above is it's quite fast and won't affect the binary size.
My expectation is that pulling in pulldown-cmark increases the binary size because we include a new crate in our binary (that is 116 kB in size), or is pulldown-cmark already a (runtime) dependency ?
Going with a treesitter integration requires installing the treesitter grammar for the language in question.
Yeah, using treesitter is more complicated because it requires a custom build step. I'm not too opinionated on if we should use treesitter or not. I think we can start prototyping with either and defer the decision to later.
Would it be sufficient to mutate the diagnostic.range or message.range directly by adding the offset?
Yep! I was working on it yesterday and that's also the route I've chosen to go down. Sorry for the confusion, I should've waiting until I had a fully fleshed out design before weighing in.
My expectation is that pulling in pulldown-cmark increases the binary size because we include a new crate in our binary (that is 116 kB in size), or is pulldown-cmark already a (runtime) dependency ?
It's not a runtime dependency, so it'll increase the crate because of its size, yes. I meant that it'd be less than the size delta from installing treesitter and associated grammar(s) which aren't totally necessary at this stage.
I think we can start prototyping with either and defer the decision to later.
Listing down some of the issues I see after hacking around locally:
Markdown, unlike Jupyter, is composed of discrete code blocks that don't necessarily affect each other. If we want to treat Markdown code blocks as discrete units, we'll have to rewrite most of the hot path since it's tightly coupled to a Path. As such, we have to rewrite lint_fix, lint_only, etc. to accept some sort of CodeBlock struct. Additionally, we have to figure out how to aggregate the diagnostics and display them/their fixes. If we don't want to treat them as discrete units, the code will be much simpler (almost akin to the Jupyter implementation).
The CodeBlock structure, at minimum, should contain the block's content and its offset from the top of the file (what I'm calling its "global offset"). Each diagnostic created while linting the block should have the code block's global offset added to it, meaning that when we display the line to users, they see the actual Markdown line number.
I didn't look into this, but we may need to expand UniversalNewLines to take Markdown line breaks as well, though again, I'm not sure how that works.
Unifying the Jupyter/Markdown parsers as Sources. I keep going back and forth on what the trait should entail, or if there should even be one.
Pinging @MichaReiser@charliermarsh just in case you guys have time to weigh in. I think the bare minimum question we need to answer is if we want to treat the code blocks as discrete units - I think we should, but that will require quite a bit of work.
P.S. sorry for the poor issue hygiene with the multiple closed PRs. I've been hacking around and didn't realize they're all on here.
That's helpful knowledge that you gained with your prototype. Thanks for working on it.
I want to throw in two more use cases:
We could also lint the markdown, and not just the python code in markdown documents
We could lint SQL inside of Python files. This is similar to Markdown in that statements are independent from each other but it becomes necessary to call from the python linting into the SQL linting, inverting the direction
The conclusion I'm coming too is that it's probably worth abstracting over the file types instead where Ruff provides a lint, fix, format etc. functions per file type. I don't know what the exact signature would be. These file type specific functions can then pre-process the input and e.g. call into other linters. For example, the markdown linter can call out to the python linter if it finds a python code block and then post-process the diagnostics, to patch up the line numbers.
The way this would work for SQL is that the python linter calls the SQL linter if it finds a SQL expression when traversing the AST. This is inspired by Prettier's approach where Prettier detects template-literals that are tagged with graphql (this is probably not valid syntax, I don't remember all the details):
Rome implements something very close to this design. Each language supports different capabilities (we may support linting SQL but not formatting). How these capabilities are implemented is transparent to the CLI. All the CLI cares about is that there's a lint function to call and it knows how to lint the files content.
I don't know if these alternative file extensions are just aliases or if they implies some format subtleties, but in the mean time, you can direct Ruff to process these files with:
Unfortunately, I don't think that's quite enough. There's a secondary check on the extension beyond including the file. See abde074, for example. It makes sense to me to include at least mdx and markdown. I'm not sure how common these others are.
Now that Ruff supports python code blocks in markdown, I'll hope to see ReStructuredText (rst) eventually ! also quite popular for Python doc because of sphinx
I opened #23204 to track looking for a better way to handle the myriad file extensions for markdown without needing an exhaustive list of possible matches, potentially duplicated in multiple places if/when we stabilize the feature and discover markdown files by default.
Quite an annoying feature, and definitely came as a surprise having all my docs formatted. Docs inherently use different formatting than code files. We want to avoid empty lines in markdown, align end of line comments etc, that we would not do in ordinary code. Yes, I can exclude markdown from it, but it really should be opt in to begin with. Somehow I got it simply by upgrading to ruff 0.16.7.
opt-in is worse than opt-out imo because it makes a feature that most users would probably want less discoverable (wanting to have different formatting in markdown sounds uncommon). users who don't want this behavior can easily revert all the changes it made and disable it
I agree, if a feature is default-off it is used by practically no-one. That being said, before you make it default-on, it needs to have a very good implementation to not cause disruption. I suppose this is for another issue at this point, but the problem is that default formatting for documentation and code needs to follow very different rules. Requiring every user to provide those rules separately based on path or file extensions is bad design. But then, having different built-in defaults per format is of course also a complication.
Just a single example of the different expectations. Two spaces before comment rather than trying to align them is definitely the way to go in actual code because this is much easier to maintain through edits. However, in documentation it should be obvious that we want (actual example)
My hands are full with other projects and I won't even make this an issue, but the problem at least should be in your attention and I do hope that someone intends to work on it for a true solution. No need to reply.
Activity
JonathanPlasse commentedon Mar 29, 2023
https://github.com/pydantic/pytest-examples
Does something similar.
evanrittenhouse commentedon Apr 26, 2023
I'm interested in trying to implement this. Looking at the projects listed above, it seems like code blocks are determined via Regex. Do we want to copy that approach or use a more robust Markdown parser (pulldown-cmark seems like a popular one)?
JonathanPlasse commentedon Apr 27, 2023
I would vote to use a markdown parser for robustness as you suggested.
MichaReiser commentedon Apr 29, 2023
Using a markdown parser makes sense from my view. It may be worth to also consider tree-sitter because it supports many languages.
The part that's unclear to me how we want to solve it in the short term is the mapping of column and line numbers in the
Messageemitters. Ruff supports Jupyter-notebooks today, but the line-mapping is somewhat "hacked-in" to make it work, and I'm a bit reluctant to add more exceptions to the line-number mapping.https://github.com/charliermarsh/ruff/blob/483f4799995d1aea7987e6f7ee403f0411060023/crates/ruff/src/message/text.rs#L70-L87
I assume a similar mapping will be necessary for Markdown files because we only pass the code block's source to Ruff, but we should show users the absolute line number from the start of the Markdown document.
Long-term
Long-term, we'll need to support the following two features.
Multi-language support
Ruff should support linting different file types. For example, Ruff should be able to lint SQL, python, and Markdown files. The filetype decides which specific linter Ruff uses to lint the file. This includes that the LSP is in sync with the file-types supported by the CLI and what extensions map to which languages. Rome supports this today.
Embedded Languages
The idea is that a document written in one language can contain code written in another language. Examples are:
The markdown file handler would recognize code blocks and delegate to Ruff to decide how to parse, lint, and format the code block's content. Ruff's infrastructure would correctly map the line-numbers between the "virtual" documents and the "physical" documents on disk.
evanrittenhouse commentedon Apr 29, 2023
Yup, agree with all of your points @MichaReiser. As part of the design phase I've been thinking about how to generalize to different filetypes. It's an interesting problem - I will take a look at Treesitter parsers as well. Going down that route, we could support different languages relatively easily. I am going to submit PRs for this incrementally so that we can iterate over the design. The first one will be a parser that pulls code blocks out of Markdown - I'm leaning towards using Treesitter since that architecture could make it easier to provide "plugins" for other languages in the future.
As far as the line mappings, I was planning on making a generic LineMap struct (or something along those lines) which would contain line numbers mapped to their offset in the containing document. That struct could then be reused for embedded languages, like you mentioned, mapping relative line numbers in the chunk of interest to the absolute line number of the document. It should provide a flexible way to treat code blocks differently, regardless of if it's an embedded language, a markdown code block, a Jupyter cell, etc.
I'll have to look into Messages and how they work before finalizing the code though. I've been reading through the Jupyter implementation as part of this.
MichaReiser commentedon Apr 29, 2023
Mapping line numbers should suffice for markdown documents but wouldn't be sufficient for e.g. SQL in python. I think it may actually be sufficient to simply add the byte offset of the markdown block to the range of every message/diagnostic.
evanrittenhouse commentedon Apr 29, 2023
Yup, that's basically what I'm doing - adding a
document_offsetfield to Messages and Diagnostics.As far as the SQL in Python example, I was thinking the approach could work because the
document_offsetwould be where the SQL code starts relative to the Python file. Line 1 of the SQL code could be on line 50 of the overarching .py file, so thedocument_offsetfor all diagnostics/messages in that block would be 50. Do you think there are flaws in that approach?E: sorry, not mapping line numbers. Mapping byte offsets between SQL/Python lines. I still need to figure out a concrete design though, if you couldn't tell 😅
evanrittenhouse commentedon Apr 29, 2023
Going with a treesitter integration requires installing the treesitter grammar for the language in question. While we could gate this behind a workspace
featureflag, I'd like some other folk's thoughts on it. I don't want to needlessly increase the binary size. I need to figure out how it all works to give exact an estimate of the increase, though.Advantage of
pulldown-cmarkas mentioned above is it's quite fast and won't affect the binary size. Disadvantage is that it obviously can't be used for anything except Markdown.@MichaReiser @JonathanPlasse do you guys have any thoughts?
JonathanPlasse commentedon Apr 29, 2023
It seems easier to first handle only markdown and in a second time expand with the tree-sitter grammar.
MichaReiser commentedon May 1, 2023
Which use cases require a diagnostic or message to know its document offset? Would it be sufficient to mutate the
diagnostic.rangeormessage.rangedirectly by adding the offset? I'm asking because increasing the size ofMessageandDiagnosticdecrease performance because:My expectation is that pulling in
pulldown-cmarkincreases the binary size because we include a new crate in our binary (that is 116 kB in size), or is pulldown-cmark already a (runtime) dependency ?Yeah, using treesitter is more complicated because it requires a custom build step. I'm not too opinionated on if we should use treesitter or not. I think we can start prototyping with either and defer the decision to later.
evanrittenhouse commentedon May 1, 2023
Yep! I was working on it yesterday and that's also the route I've chosen to go down. Sorry for the confusion, I should've waiting until I had a fully fleshed out design before weighing in.
It's not a runtime dependency, so it'll increase the crate because of its size, yes. I meant that it'd be less than the size delta from installing treesitter and associated grammar(s) which aren't totally necessary at this stage.
Cool!
evanrittenhouse commentedon Jun 29, 2023
Listing down some of the issues I see after hacking around locally:
Path. As such, we have to rewritelint_fix,lint_only, etc. to accept some sort ofCodeBlockstruct. Additionally, we have to figure out how to aggregate the diagnostics and display them/their fixes. If we don't want to treat them as discrete units, the code will be much simpler (almost akin to the Jupyter implementation).CodeBlockstructure, at minimum, should contain the block's content and its offset from the top of the file (what I'm calling its "global offset"). Each diagnostic created while linting the block should have the code block's global offset added to it, meaning that when we display the line to users, they see the actual Markdown line number.UniversalNewLinesto take Markdown line breaks as well, though again, I'm not sure how that works.Sources. I keep going back and forth on what the trait should entail, or if there should even be one.Pinging @MichaReiser @charliermarsh just in case you guys have time to weigh in. I think the bare minimum question we need to answer is if we want to treat the code blocks as discrete units - I think we should, but that will require quite a bit of work.
P.S. sorry for the poor issue hygiene with the multiple closed PRs. I've been hacking around and didn't realize they're all on here.
MichaReiser commentedon Jun 30, 2023
That's helpful knowledge that you gained with your prototype. Thanks for working on it.
I want to throw in two more use cases:
The conclusion I'm coming too is that it's probably worth abstracting over the file types instead where Ruff provides a
lint,fix,formatetc. functions per file type. I don't know what the exact signature would be. These file type specific functions can then pre-process the input and e.g. call into other linters. For example, the markdown linter can call out to the python linter if it finds a python code block and then post-process the diagnostics, to patch up the line numbers.The way this would work for SQL is that the python linter calls the SQL linter if it finds a SQL expression when traversing the AST. This is inspired by Prettier's approach where Prettier detects template-literals that are tagged with
graphql(this is probably not valid syntax, I don't remember all the details):Rome implements something very close to this design. Each language supports different capabilities (we may support linting SQL but not formatting). How these capabilities are implemented is transparent to the CLI. All the CLI cares about is that there's a
lintfunction to call and it knows how to lint the files content.Definition of the JavaScript file type:
https://github.com/rome/tools/blob/38104b339da8ff688f469799e1fc3f4a46f3d2ec/crates/rome_service/src/file_handlers/javascript.rs#L86-L124
File agnostic API:
https://github.com/rome/tools/blob/38104b339da8ff688f469799e1fc3f4a46f3d2ec/crates/rome_service/src/workspace/server.rs#L446-L457
paddyroddy commentedon Jun 30, 2023
@evanrittenhouse I was definitely considering them as discrete units when I raised this. For example here https://github.com/astro-informatics/sleplet/blob/c510795e7ebd91000b8afe53276e522b75cdfbb6/.github/workflows/examples.yml#L33 I use pytest-codeblocks to run some example code blocks (essentially acting as another type of test).
48 remaining items
kdeldycke commentedon Feb 9, 2026
I don't know if these alternative file extensions are just aliases or if they implies some format subtleties, but in the mean time, you can direct Ruff to process these files with:
ntBre commentedon Feb 9, 2026
Unfortunately, I don't think that's quite enough. There's a secondary check on the extension beyond including the file. See abde074, for example. It makes sense to me to include at least
mdxandmarkdown. I'm not sure how common these others are.Avasam commentedon Feb 9, 2026
For the curious, MDX is a mix of markdown and jsx: https://mdxjs.com / https://github.com/mdx-js/mdx
Now that Ruff supports python code blocks in markdown, I'll hope to see ReStructuredText (rst) eventually ! also quite popular for Python doc because of sphinx
amyreese commentedon Feb 10, 2026
I opened #23204 to track looking for a better way to handle the myriad file extensions for markdown without needing an exhaustive list of possible matches, potentially duplicated in multiple places if/when we stabilize the feature and discover markdown files by default.
Drop explicit support for `.qmd` file extension
Discover markdown files by default in preview mode (astral-sh#23434)
Remove `extend-include` for Markdown files
Don't format unlabeled markdown code blocks (#23106)
ddelange commentedon Jun 27, 2026
@amyreese thanks for pushing this through! what's the timeline for this to move out of preview?
MichaReiser commentedon Jun 27, 2026
Our current plan is to stabilize this feature with the next minor, which we plan to do in the next few weeks.
LeoVasanko commentedon Sep 13, 2026
Quite an annoying feature, and definitely came as a surprise having all my docs formatted. Docs inherently use different formatting than code files. We want to avoid empty lines in markdown, align end of line comments etc, that we would not do in ordinary code. Yes, I can exclude markdown from it, but it really should be opt in to begin with. Somehow I got it simply by upgrading to ruff 0.16.7.
DetachHead commentedon Sep 13, 2026
opt-in is worse than opt-out imo because it makes a feature that most users would probably want less discoverable (wanting to have different formatting in markdown sounds uncommon). users who don't want this behavior can easily revert all the changes it made and disable it
LeoVasanko commentedon Sep 13, 2026
I agree, if a feature is default-off it is used by practically no-one. That being said, before you make it default-on, it needs to have a very good implementation to not cause disruption. I suppose this is for another issue at this point, but the problem is that default formatting for documentation and code needs to follow very different rules. Requiring every user to provide those rules separately based on path or file extensions is bad design. But then, having different built-in defaults per format is of course also a complication.
Just a single example of the different expectations. Two spaces before comment rather than trying to align them is definitely the way to go in actual code because this is much easier to maintain through edits. However, in documentation it should be obvious that we want (actual example)
Instead of (as now formatted by ruff)
My hands are full with other projects and I won't even make this an issue, but the problem at least should be in your attention and I do hope that someone intends to work on it for a true solution. No need to reply.