Embedded Syntax Highlighting in Neovim with Nix Multiline Strings

GitHub flavored markdown has a neat feature where you can specify what language you want highlighted in a code block:

```nix

I was wondering, how to set this up with nix files and multiline strings in Neovim. Something like:

''lua

Bonus if the block can also leverage LSP support for the given language.

There were a couple of suggestions here:

Some of the suggestions were:

My problem stems from the fact that I would like to use nix paths in my lua configs and so referencing them externally is not possible.

Here’s my config if you want to see an example:

Relevant discussion:

What you’re looking for is called “language injection”.
For neovim you can install the nvim-treesitter plugin with the Nix parser (and more parsers for the language you wish to highlight). If you use the unstable channel nvim-treesitter should have some of these injections by default: for example it should highlight writeScript and buildPhase as bash, etc.

I’m currently using plugin = nvim-treesitter.withAllGrammars; # Syntax Highlighting in my config and I am also on unstable. Is there something else that I need to add? I also tried adding /* lua */ in front of my multiline strings but that didn’t work either.

/* language */ nix injections are not implemented in nvim-treesitter yet. It was previously not possible without adding directives, so I opened feat(treesitter): allow capture text to be transformed by figsoda · Pull Request #21548 · neovim/neovim · GitHub, and I’ll implement the nvim-treesitter part once that 0.9.0 is stable.

4 Likes

An update on the issue, opened injections(nix): dynamic language injection via comments by figsoda · Pull Request #4658 · nvim-treesitter/nvim-treesitter · GitHub to implement the feature upstream, and neovim-unwrapped: apply patch to fix the `#gsub!` directive by figsoda · Pull Request #226323 · NixOS/nixpkgs · GitHub to backport a required bugfix to nixpkgs

2 Likes