Preview Markdown Documents in BBEdit

A quickie: here’s a way of directly previewing Markdown documents in the BBEdit preview window using PHP. (Inspired by this Python method that does the same thing).

  1. Make a template file (you’ll probably want to add some styles to this).
~/Sites/markdown-preview/template.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Markdown Preview</title>
</head>
<body>
##markdown##
</body>
</html>
  1. Make the php file, and follow the instructions in the PHP comments.
~/Sites/markdown-preview/index.php
<?php

/*
* Download these and put them somewhere in your php path:
*
* [http://www.michelf.com/projects/php-markdown/](http://www.michelf.com/projects/php-markdown/)
* [http://www.michelf.com/projects/php-smartypants/](http://www.michelf.com/projects/php-smartypants/)
*/
include_once 'markdown.php';
include_once 'smartypants.php';

/*
* You'll need to change this:
*/
$markdownDocsDir = isset ($_SERVER['MARKDOWN_DOCS_DIR']) ? $_SERVER['MARKDOWN_DOCS_DIR'] : '/Users/username/Documents';

/*
* You'll need to set up BBEdit to use something like this as the Preview Server URL:
*
* http://localhost/markdown-preview/?file=/
*/
$file = $_GET['file'];
$text = file_get_contents ($markdownDocsDir . $file);
$formatted = SmartyPants(Markdown($text), '2');

/*
* Display the formatted text via a simple template.
*/
$templateFile = './template.html';
$templateText = file_exists ($templateFile) ? file_get_contents ($templateFile) : "##markdown##";
echo (str_replace ('##markdown##', $formatted, $templateText));

?>

Comments