Use a custom markdown library in Drupal 7

Code needed

We used the latest version of the same markdown processor, so first you have to download it from github or (as we did) just clone the library an use the master version (named lib). Shout out to Michel Fortin for this great library.


cd sites/all/libraries
git clone https://github.com/michelf/php-markdown.git

Since we're going to override the behavior of the default markdown module we need to implement some hooks.

First we need to register our library using hook_libraries_info.


/**
 * Implements hook_libraries_info().
 */
function MY_MODULE_libraries_info() {
  $libraries['php-markdown'] = array(
    'name' => 'PHP Markdown Extra plugin',
    'vendor url' => 'https://github.com/michelf/php-markdown/',
    'download url' => 'https://github.com/michelf/php-markdown/archive/1.4.1.zip',
    'version' => '1.4.1',
    'files' => array(
      'php' => array(
        'Michelf/MarkdownInterface.php',
        'Michelf/Markdown.php',
        'Michelf/MarkdownExtra.php',
      ),
    ),
  );

  return $libraries;
}

We also need to override the default process callback from the markdown function.


/**
 * Implements hook_filter_info_alter().
 */
function MY_MODULE_filter_info_alter(&$info) {
  $info['filter_markdown']['process callback'] = '_MY_MODULE_filter_markdown';
}

/**
 * Filter process callback.
 */
function _MY_MODULE_filter_markdown($text, $format) {
  if (!empty($text)) {
    libraries_load('php-markdown');
    $text = \Michelf\MarkdownExtra::defaultTransform($text);
  }

  return $text;
}

Why should you want to do this.

We did it because we needed to be able to add data attributes to images in markdown, so we could use the picture module to output responsive images. But if you want to support id or class attributes you need to use a new version as well.

Example


An image with a data attribute.  
![A nice picture](/sites/default/files/example.png){data-picture-mapping=blog}

An image with a class.  
![A nice picture](/sites/default/files/example.png){.inset-image}