How to get Ranger to preview Markdown files

Pretty-up your file manager

Ranger has a really nifty preview pane on its right hand side that tries to give you an idea of what a file is before you open it. This is mainly why I use it at all - rather than open and close every single PDF or image in a folder, I can simply flip through them. Same goes with text.

That’s when I wondered if it would be possible for it to show the formatting in Markdown files rather than just the plain text versions. Turns out it is, and it’s pretty easy!

Take a look below.

Before the change.

You can see above that the file is previewed on the right in plain text.

After the change.

Now you can see that the pound signs are gone, the numbered list is actually numbered and the code is indented.

It’s not perfect, the horizontal rule isn’t there and it’s lacking some colour, but as a quick way to tidy up the preview it’s not bad.

How you can do this

You’ll need npm to get the required package installed, on my distro (Arch) it was in the repositories so it was

sudo pacman -S npm

Then you want to install ansimd with npm. This is what creates an output from markdown files that is readable in the terminal.

To do this I just had to do

sudo npm install ansimd -g

Then you need to edit your ~/.config/ranger/scope.sh with the following in the $extension section:

# Markdown files
    markdown|md)
        try ansimd "$path" && { dump | trim; exit 5; } || exit 2;;

Put it after any ;; but before the esac line.

All done! Open ranger, hover over a markdown file, and you’ll see it’s formatted now.

Notes

  • If you don’t have a scope.sh you need to run ranger --copy-config=scope - it’ll give you a good sample one. If you don’t have ANYTHING (notably rifle.conf) then do ranger --copy-config=all
  • You may use other extensions for markdown files. I have included markdown and md but if you have your own it’s easy to include them like so: markdown|md|mrkdwn|etc|etc)
  • For the curious, exit 5 means ‘display without doing anything’ and exit 2 happens upon failure and means ‘display as plain text’. That way if you don’t have ansimd installed you’ll still get the old plaintext preview.
  • There may be better ways to do this, please tell me if you have any!