(HACK) Sphinx + reStructured Text + FSWATCH = Live Preview

Sphinx + reStructured Text is great for documenting Python project, but I always missed some kind of live preview editor. I finally found a hacky solution to automate the task of rebuilding html and reloading browser using a combination of fswatch and Apple script. Note that the solution will only work for Mac Users. Windows users might be able to find some alternative solution based on this.

Below are the three steps to get live preview kind of setup.

1. Install fswatch.

I am assuming you already have homebrew installed. If not, please find instructions over here. Once you have homebrew, installing fswatch is a breeze.

# Homebrew
$ brew install fswatch

2. Write an Apple Script to reload active tab of a browser.

Copy the below Apple Script and save it in your home folder as reloadChrome.sh. This script tells Google Chrome browser to reload its active browser.

#!/bin/sh
exec <"$0" || exit; read v; read v; exec /usr/bin/osascript - "$@"; exit

tell application "Google Chrome"
    reload active tab of window 1
end tell

Make sure that the script is executable: $ chmod +x ~/reloadChrome.sh

3. Start fswatch

Now inside your sphinx docs folder run the following command from terminal.

fswatch -r -0 ../myproject/ | xargs -0 -I % sh -c "make html; ~/reloadChrome.sh"

Open a Google Chrome browser and in the active tab open your local sphinx documentation. Once done, start updating your docstring. Every time you save the file, fswatch will fire an event and eventually xargs will execute make html command and finally reloadChrome.sh will reload the active tab. With two screens you will have (nearly) live preview kind of setup.

Enjoy writing your docstring in reStructured Text format.

Posted in General | Leave a comment