Nixpkgs-fmt on embedded snippets in Markdown?

Does anyone know of attempts or tools that let you run a code formatter on the embedded language snippets in a Markdown file?

I’ve seen other OSS projects do this and I love the consistency it brings to code samples.
I was hoping to explore something similar for nixpkgs documentation.

The context is me working on docs: improve Rust language guide · Pull Request #141288 · NixOS/nixpkgs · GitHub. I have added more nix expressions and would love to have an automated tool for formatting those embedded snippets.

An alternative would be to define a simple literate programming structure for working with Markdown. Define nix expression snippets in a subdirectory and then interpolate them into the final markdown file. That feels like a bigger change that creates potential learning obstacles though.

2 Likes

I have written a pandoc filter that can be used in this way, but that also formats the entire document with pandoc, which may or may not be something we want.

3 Likes

Nice!

Would I be able to configure that pandoc filter to use nixpkgs-fmt instead of nixfmt?

You should be able to do something like

formatters:
   nix: nixpkgs-fmt

but I’m having trouble getting that to work for some reason…

That sounds great. If you are able, could you post the source to what you are trying? I wasn’t sure where the formatters: config would go. I may also be of use troubleshooting the error!

It seems like the following works, but more complicated test cases fail:

---
formatters:
  nix: nixpkgs-fmt
---

``` nix
{ foo
        }: foo
```

asdf asdf
pandoc --from markdown --to markdown --filter main.py test.md

But if I try for example:

---
formatters:
  nix: nixpkgs-fmt
---

``` nix
{ foo
        }: foo
```

asdf asdf

``` haskell
foo :: a -> a
foo = id
```

It fails with:

Error running filter main.py:
Error in $.blocks[2]: parsing Text failed, expected String, but encountered Array
1 Like

Wait it was a bug in my code, I’ll push a fix to github done.

1 Like

Try something like this from the nixpkgs folder:

pandoc --from markdown --to markdown --metadata-file /tmp/meta.yaml --filter  ~/devel/pandoc-formatters/main.py doc/stdenv/stdenv.chapter.md

With /tmp/meta.yaml being:

---
formatters:
    nix: nixpkgs-fmt
---

Perfect!

I tried that out and it does what I need.
We can continue further in header anchors are truncated · Issue #1 · Synthetica9/pandoc-formatters · GitHub !