Skip to content

Apply ruff formatting to markdown code blocks #3792

Closed
10 of 10 issues completed
Closed

Description

@paddyroddy

It would be cool to have the functionality to run ruff over python codeblocks like this does for black https://github.com/adamchainz/blacken-docs

Sub-issues

Sub-issues

10 of 10 Issues completed
Loading 10 sub-issues

Activity

  1. JonathanPlasse commented on Mar 29, 2023

    @JonathanPlasse
    Contributor
  2. added
    wish
    on Mar 29, 2023
  3. evanrittenhouse commented on Apr 26, 2023

    @evanrittenhouse
    Contributor

    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)?

  4. JonathanPlasse commented on Apr 27, 2023

    @JonathanPlasse
    Contributor

    I would vote to use a markdown parser for robustness as you suggested.

  5. MichaReiser commented on Apr 29, 2023

    @MichaReiser
    Member

    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:

    • 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.

  6. evanrittenhouse commented on Apr 29, 2023

    @evanrittenhouse
    Contributor

    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.

  7. MichaReiser commented on Apr 29, 2023

    @MichaReiser
    Member

    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.

  8. evanrittenhouse commented on Apr 29, 2023

    @evanrittenhouse
    Contributor

    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 😅

  9. evanrittenhouse commented on Apr 29, 2023

    @evanrittenhouse
    Contributor

    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.

    @MichaReiser @JonathanPlasse do you guys have any thoughts?

  10. JonathanPlasse commented on Apr 29, 2023

    @JonathanPlasse
    Contributor

    It seems easier to first handle only markdown and in a second time expand with the tree-sitter grammar.

  11. MichaReiser commented on May 1, 2023

    @MichaReiser
    Member

    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.

  12. evanrittenhouse commented on May 1, 2023

    @evanrittenhouse
    Contributor

    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.

    Cool!

  13. evanrittenhouse commented on Jun 29, 2023

    @evanrittenhouse
    Contributor

    Listing down some of the issues I see after hacking around locally:

    1. 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).
    2. 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.
    3. 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.
    4. 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.

  14. MichaReiser commented on Jun 30, 2023

    @MichaReiser
    Member

    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):

    let result = useQuery(graphql`
    	query myQuery() {
    	}
    `);

    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.

    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

  15. paddyroddy commented on Jun 30, 2023

    @paddyroddy
    Author

    @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).

  16. 48 remaining items

  17. kdeldycke commented on Feb 9, 2026

    @kdeldycke

    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:

    [tool.ruff]
    extend-include = [ "*.{markdown,mdown,mkdn,mdwn,mkd,md,mdtxt,mdtext,mdx}" ]
  18. ntBre commented on Feb 9, 2026

    @ntBre
    Contributor

    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.

  19. Avasam commented on Feb 9, 2026

    @Avasam
    Contributor

    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

  20. amyreese commented on Feb 10, 2026

    @amyreese
    Contributor

    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.

  21. added a commit that references this issue on Mar 5, 2026
    9a70f5e
  22. ddelange commented on Jun 27, 2026

    @ddelange

    @amyreese thanks for pushing this through! what's the timeline for this to move out of preview?

  23. MichaReiser commented on Jun 27, 2026

    @MichaReiser
    Member

    Our current plan is to stabilize this feature with the next minor, which we plan to do in the next few weeks.

  24. LeoVasanko commented on Sep 13, 2026

    @LeoVasanko

    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.

  25. DetachHead commented on Sep 13, 2026

    @DetachHead
    Contributor

    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

  26. LeoVasanko commented on Sep 13, 2026

    @LeoVasanko

    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)

    r.pretty    # "Facebook"
    r.kind      # "social"
    r.provider  # "Meta"
    r.url       # "http://www.facebook.com/externalhit_uatext.php"

    Instead of (as now formatted by ruff)

    r.pretty  # "Facebook"
    r.kind  # "social"
    r.provider  # "Meta"
    r.url  # "http://www.facebook.com/externalhit_uatext.php"

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

formatter

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions