Asciidoctor, Guard, nixpkgs live reloading writing environment

This post describes creating an Asciidoctor live reloading writing environment using Guard with Nix.

With this environment saving updates to an asciidoc will result in a preview automatically being re-loaded in a web browser.

Create a project folder

mkdir asciidocs

Create a Nix shell environment

file asciidocs/default.nix:

with import <nixpkgs> {};

stdenv.mkDerivation rec {
  name = "asciidoctor-env";

  shellHook = ''
    alias run="bundle exec guard" #(1)
    bundle install #(2)
  '';

  buildInputs = [ #(3)
    bundler
    ruby_2_3
  ];
}

File details:

  1. Create an alias run which can be used to watch file changes and live reload in the shell.
  2. When the shell starts run bundle install to make sure all Asciidotor and Guard dependencies are available.
  3. Makes bundler and Ruby available to the shell path

Create a Gemfile

Create a gem file to install the required asciidoctor and guard Ruby gem depdencies.

file asciidocs/Gemfile

source 'https://rubygems.org'

gem 'asciidoctor'
gem 'guard'
gem 'guard-shell'
gem 'guard-livereload'
gem 'yajl-ruby'

Start a nix shell

Start a nix shell from the project directory which will automatically run bundle insall installing the above gems and create a Gemfile.lock.

nix-shell

Create a Guard file

File asciidocs/Guardfile

require 'asciidoctor'

guard :shell do
  watch(%r{^.+\.adoc}) do |m|
    Asciidoctor.render_file(m[0], {:safe => 'unsafe'})
  end
end

guard 'livereload' do
  watch(%r{^.+\.(css|js|html)$})
end

Start guard

From the nix shell start Guard which will then watch for asciidoc file changes.

run

Alternativley

bundle exec guard

Install the LiveReload browser plugin

Download the LiveReload plugin from below.

  • Chrome - https://chrome.google.com/webstore/detail/livereload/jnihajbhpnppcggbcgedagnkighmdlei
  • Firefox - https://addons.mozilla.org/en-US/firefox/addon/livereload/

Open the Asciidoctor generated html in your browser

Open the Asciidoctor generated html file in your web browser. Click the live reload button to enable live reloading.

With live reloading enabled, every time an update is made to the Asciidoc file the changes will be re-loaded in the browser.

This recipe was created after trying to package Guard on Nix. Guard could not see the GEM_PATH for Asciidoctor.