nani.wtf/src/posts/2022-10-16-tangling-org-fil...

1.6 KiB

title keywords image series
Tangling Org files with Nix nix, emacs, org-mode ./images/nix_banner.png Nix shorts

Tangling Org files with Nix

One of the great wonders about Emacs Org Mode is its builtin functionality for literate programming. This allows us to write code inbetween text as if it was a research article, or a markdown file, but still export and run the code. By using emacs, we can keep our source files as articles, and only extract the source code when we export the code to the nix store.

Example

# hello_world.org

#+TITLE: How to write hello world in javascript
#+AUTHOR: h7x4
#+PROPERTY: header-args :js :tangle yes

Here's how:

#+BEGIN_SRC js
  console.log("Hello World");
#+END_SRC

Woah!
# default.nix
{ pkgs, stdenvNoCC }:
stdenvNoCC.mkDerivation {
  name = "hello-world-js";
  src = ./.;

  buildInputs = with pkgs; [ emacs ];
  buildPhase = ''
    emacs --batch -l org hello_world.org -f org-babel-tangle
  '';

  installPhase = ''
    cp hello_world.js $out
  '';
}

Tangling Nix Code?

Unfortunately, this isn't as declarative as the previous part. If we were to process literate nix using a nix file, it would end up in the nix store. That would require us to use import from derivation, which brings all sorts of whackiness.

Instead, you should probably use emacs interactively to tangle the nix files, or just keep the nix files raw altogether.