Convert Nix expression to text

Hi,

I’m trying to output a Nix expression to a file when building a devshell. I can accomplish this by just simply writing the expression as a string and then outputting it like so:

{
  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs";
    flake-utils.url = "github:numtide/flake-utils";
  };

  outputs = { self, nixpkgs, flake-utils }:
    flake-utils.lib.eachDefaultSystem (system:
      let
       pkgs = import nixpkgs {
          inherit system;
        };

        expr = ''
        { config, pkgs, ... }:
          {
            packages = [
              pkgs.hello
            ];
          }
        '';
      in
      {
        devShell = pkgs.mkShell {
          shellHook = ''
            cat <<EOT > /path/to/file.nix
              ${expr}
            EOT
          '';
        };
      }
    );
}

However, for the sake of maintenance, it’d be nice to have my IDE apply syntax highlighting/linting to the embedded expression. Is there a way to define the above outside of a string and then convert it to a string later?

Not that I am aware of, though depending on your editor, you might be able to configure it in a way that it considers all strings as written in another syntax, depending on a magic comment you have to add to every single string then.

I tried something like that with Emacs and polymode, but it didn’t work out. At the end I just used extra files with proper endings and builrins.readFile

1 Like

I’ve been using GitHub - twlz0ne/separedit.el: Edit comment or string/docstring or code block inside them in separate buffer with your favorite mode lately, which does a pretty good job at this. Bit buggy still, but it has upstream nix support, and is getting better with every issue :slight_smile:

Try putting the expression in another file, and then reading it with builtins.readFile

https://nixos.org/manual/nix/stable/expressions/builtins.html#builtins-readFile