Просмотр исходного кода

Merge pull request #775 from mikitex70/master

PlantUML: add support for Markdown syntax
Justin Mayer лет назад: 8
Родитель
Сommit
448886902b

+ 2 - 0
.gitignore

@@ -1,5 +1,7 @@
 *.pyc
 *.log
 *~
+.directory
+.idea
 .project
 .pydevproject

+ 1 - 1
better_code_samples

@@ -1 +1 @@
-Subproject commit 8ae86dcddb4f65d0e6b5f1afe84b6afdb4297668
+Subproject commit 91717a204bbd0ae4a1af6fe25ac5dd783fb4a7db

+ 1 - 1
bootstrapify

@@ -1 +1 @@
-Subproject commit b3e3d9e669c44aff6b872c4d45448718b1f87e2c
+Subproject commit bc4e0a1bf274425a777f0b613c4199b2a5857ff8

+ 1 - 1
cjk-auto-spacing

@@ -1 +1 @@
-Subproject commit c56a09a823bc1d5ea97404bc33e09f37adb01df6
+Subproject commit 92346597b86f3ff85217871a42b404e30ec4f9ec

+ 1 - 1
pelican-gist

@@ -1 +1 @@
-Subproject commit d8205680a91dbb158de17f38a182693f5af7691c
+Subproject commit 4cce3dad9e7d03511bd04734def69f5fe2958ee5

+ 1 - 1
pelican-githubprojects

@@ -1 +1 @@
-Subproject commit c1590cb566e98a643b121c3571d0787a2dec2159
+Subproject commit f55b497dcc37c81791ef0e294a1b1c710a933ca6

+ 1 - 1
pelican-jinja2content

@@ -1 +1 @@
-Subproject commit f73ef9b1ef1ee1f56c80757b4190b53f8cd607d1
+Subproject commit 9adc69f786a673d37322235c35119f38feb153c4

+ 1 - 1
pelican-langcategory

@@ -1 +1 @@
-Subproject commit d05e7d6a8bdab9de8cf505615b82ad15866c56ab
+Subproject commit 94fc0bc2983e92d954708611b36448724bf71616

+ 1 - 1
pelican-page-hierarchy

@@ -1 +1 @@
-Subproject commit ad7c9879147bf82dc8c66e50ef464ecec4c8972c
+Subproject commit f11b533a50aa58800d1eade4aa6d3dfa17fd0f5c

+ 1 - 1
pelican_vimeo

@@ -1 +1 @@
-Subproject commit 1dd1a04768ff0d800c1f8edaa23ca100a5d76eab
+Subproject commit d18f1ddfe9fc76230409ed3eff1502f2fcd338c9

+ 1 - 1
pelican_youtube

@@ -1 +1 @@
-Subproject commit 0b72fdaf9dbbf2800bc0a463fbedd372b87808cd
+Subproject commit 045c43dd4deb56731366c13d54a41a5adf8fe66b

+ 1 - 1
pelicanfly

@@ -1 +1 @@
-Subproject commit fedfa1d40a20f6a41d419addd529b9b03591091e
+Subproject commit 265865f693092f6409f4e4ef451ff7543fa4e350

+ 1 - 1
pelicanthemes-generator

@@ -1 +1 @@
-Subproject commit 6d05b3a919dd9dcad6f472c51b210a6b9afdb46b
+Subproject commit 916f5a570fcd7c4042917642571f4fda6d42ee38

+ 1 - 1
pin_to_top

@@ -1 +1 @@
-Subproject commit fb34938931bb7c56af9fcd1043af5ac55e5d5c49
+Subproject commit 4c022ecbd958cbf5538e06d5bd233d048902dad4

+ 114 - 27
plantuml/Readme.rst

@@ -1,32 +1,27 @@
-PlantUML plugin for Pelican rst documents
-=========================================
+================================================
+PlantUML plugin for Pelican rst and md documents
+================================================
 
-This plugin allows you to define UML diagrams directly into rst documents using the great
-PlantUML_ tool.
+This plugin allows you to define UML diagrams directly into rst or md documents using the great PlantUML_ tool.
 
-This plugin gets the content of ``uml`` directive, passes it to the external
-program PlantUML_ and then links the generated image to the document.
+It gets the content of ``uml`` directive, passes it to the external program PlantUML_ and then links the generated image to the document.
+
+.. contents::
 
 Installation
-------------
+============
 
-You need to install PlantUML_ (see the site for details) and Graphviz_ 2.26.3 or later.
-The plugin expects a program ``plantuml`` in the classpath. If not installed by your package
-manager, you can create a shell script and place it somewhere in the classpath. For example,
-save te following into ``/usr/local/bin/plantuml`` (supposing PlantUML_ installed into
-``/opt/plantuml``):
+You need to install PlantUML_ (see the site for details) and Graphviz_ 2.26.3 or later. The plugin expects a program ``plantuml`` in the classpath. If not installed by your package manager, you can create a shell script and place it somewhere in the classpath. For example, save te following into ``/usr/local/bin/plantuml`` (supposing PlantUML_ installed into ``/opt/plantuml``):
 
 .. code-block:: bash
 
     #!/bin/bash
     java -jar /opt/plantuml/plantuml.jar ${@}
 
-For Gentoo_ there is an ebuild at http://gpo.zugaina.org/dev-util/plantuml/RDep: you can download
-the ebuild and the ``files`` subfolder or you can add the ``zugaina`` repository with _layman
-(raccomended).
+For Gentoo_ there is an ebuild at http://gpo.zugaina.org/dev-util/plantuml/RDep: you can download the ebuild and the ``files`` subfolder or you can add the ``zugaina`` repository with _layman (reccomended).
 
 Usage
------
+=====
 
 Add ``plantuml`` to plugin list in ``pelicanconf.py``. For example:
 
@@ -34,27 +29,88 @@ Add ``plantuml`` to plugin list in ``pelicanconf.py``. For example:
 
     PLUGINS = [ "sitemap", "plantuml" ]
 
-Use the ``uml`` directive to start UML diagram description. It is not necessary to enclose
-diagram body between ``@startuml`` and ``@enduml`` directives: they are added automatically 
-before calling ``plantuml``.
+One loaded the plugin register also the Pyhton-Markdown_ extension. 
+
+RST usage
+---------
+Use the ``uml`` directive to start UML diagram description. It is not necessary to enclose diagram body between ``@startuml`` and ``@enduml`` directives: they are added automatically  before calling ``plantuml``.
+
+In addition to ``class`` and ``alt`` options common to all images, you can use the ``format`` option to select what kind of image must be produced. At the moment only ``png`` and ``svg`` are supported; the default is ``png``.
+
+Please note that the ``format`` option in not recognized by the ``plantuml`` extension of ``rst2pdf`` utility (call it with ``-e plantuml.py``) so if you use it you can get errors from that program.
+
+MD usage
+--------
+For use with the Pyhton-Markdown_ syntax, the UML block must be enclose with ``::uml::``:
+
+.. code-block:: markdown
+
+    ::uml:: [format=...] [classes=...] [alt=...]
+       PlantUML script
+    ::end-uml::
+
+Please keep a blank line before ``::uml::`` and after ``::end-uml::`` to be sure that the UML code will be correctly recognized. See Examples_ for more details.
+
+With MD syntax options must be specified in the same line as the opening ``:uml::``, with the order ``format``, ``classes`` anmd ``alt``. The general syntax for option is
+
+.. code-block:: text
+
+    option="value"
+
+Option can be enclosed with single or double quotes, as you like. Options defaults are the same as for the rst plugin.
+
+For pandoc_reader plugin users
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+The plugin ``pandoc_reader`` sends the Markdown body to the pandoc_ tool which has it's own Markdown parser, written in Haskell_ language: Python_ plugins manipulating Markdown posts (such this) are not used because the entire body id passed to pandoc_ without any iteraction by Pelican_.
+
+For those who are using the ``pandoc_reader`` plugin and wants to include PlantUML_ diagrams, use the ``pandoc-plantuml`` script (only *nix, sorry): it is a wrapper for filtering the code blocks parsed by pandoc_ before
+writing out the converted file. It is an adaption of the great work by Kurt Bonne for his `pandoc-plantuml-filter <https://github.com/kbonne/pandoc-plantuml-filter.git>`_.
+
+To use it, copy the ``pandoc-plantuml`` file in a subdirectory of your pelican project (for example `pandoc_extensions`) and make sure it is executable (``chmod +x pandoc-plantuml``).
+
+In the ``pelicanconf.py`` configure the needed plugins:
+
+.. code-block:: python
 
-In addition to ``class`` and
-``alt`` options common to all images, you can use the ``format`` option to select what kind
-of image must be produced. At the moment only ``png`` and ``svg`` are supported; the default
-is ``png``.
+    PLUGINS = ['pandoc_reader'] // Yes, plantuml plugin non necessary
+    PANDOC_ARGS = ['--filter=pandoc_extensions/pandoc-plantuml']
+
+In Markdown posts use the following syntax to include PlantUML_ diagrams:
+
+.. code-block:: markdown
+
+    ```plantuml
+    @startuml
+      Alice -> Bob: Authentication Request
+      Bob --> Alice: Authentication Response
+
+      Alice -> Bob: Another authentication Request
+      Alice <-- Bob: another authentication Response
+    @enduml
+    ```
+
+Rendered images will bu put in the output/images folder.
+
+**NOTE:** ``pandoc-plantuml`` is broken from pandoc 1.16 cause an API change in pandoc ``Image`` function. I'm working on a fix but in the meanwhile use a version of pandoc prior to ``1.16`` .
+
+Debugging
+---------
+The plugin can produce debugging informations to help to locate errors. To enable debugging execute ``pelican`` in debug mode:
+
+ .. code-block:: console
+
+     make DEBUG=1 html
 
-Please note that the ``format`` option in not recognized by the ``plantuml`` extension of
-``rst2pdf`` utility (call it with ``-e plantuml.py``) so if you use it you can get errors from
-that program.
   
 Examples
---------
+========
 
 Sequence diagram (from PlantUML_ site):
 
 .. code-block:: rst
 
   .. uml::
+    :alt: Sample sequence diagram
 
     participant User
 
@@ -76,6 +132,31 @@ Sequence diagram (from PlantUML_ site):
 Output:
 
 .. image:: http://plantuml.sourceforge.net/imgp/sequence_022.png
+   :alt: Sample sequence diagram
+
+
+Same diagram with Pyhton-Markdown_ syntax:
+
+.. code-block:: markdown
+
+    ::uml:: format="png" alt="Sample sequence diagram"
+      participant User
+
+      User -> A: DoWork
+      activate A #FFBBBB
+
+      A -> A: Internal call
+      activate A #DarkSalmon
+
+      A -> B: << createRequest >>
+      activate B
+
+      B --> A: RequestCreated
+      deactivate B
+      deactivate A
+      A -> User: Done
+      deactivate A
+    ::end-uml::
 
 Another example from PlantUML_ site (activity diagram):
 
@@ -119,6 +200,7 @@ Another example from PlantUML_ site (activity diagram):
 Generated image:
 
 .. image:: http://plantuml.sourceforge.net/imgp/activity2_009.png
+   :alt: Sample activity diagram
 
 
 
@@ -127,3 +209,8 @@ Generated image:
 .. _Gentoo: http://www.gentoo.org
 .. _layman: http://wiki.gentoo.org/wiki/Layman
 .. _Graphviz: http://www.graphviz.org
+.. _Pyhton-Markdown: http://pythonhosted.org/Markdown
+.. _pandoc: http://johnmacfarlane.net/pandoc
+.. _Haskell: http://www.haskell.org/haskellwiki/Haskell
+.. _Python:: http://www.python.org
+.. _Pelican: http://docs.getpelican.com/en

+ 1 - 1
plantuml/__init__.py

@@ -1 +1 @@
-from plantuml_rst import *
+from .plantuml_rst import *

+ 58 - 0
plantuml/generateUmlDiagram.py

@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+import logging
+import os
+import tempfile
+from zlib import adler32
+from subprocess import Popen, PIPE
+from pelican import logger
+
+
+def generate_uml_image(path, plantuml_code, imgformat):
+    tf = tempfile.NamedTemporaryFile(delete=False)
+    tf.write('@startuml\n'.encode('utf8'))
+    tf.write(plantuml_code.encode('utf8'))
+    tf.write('\n@enduml'.encode('utf8'))
+    tf.flush()
+
+    logger.debug("[plantuml] Temporary PlantUML source at "+(tf.name))
+
+    if imgformat == 'png':
+        imgext = ".png"
+        outopt = "-tpng"
+    elif imgformat == 'svg':
+        imgext = ".svg"
+        outopt = "-tsvg"
+    else:
+        logger.error("Bad uml image format '"+imgformat+"', using png")
+        imgext = ".png"
+        outopt = "-tpng"
+
+    # make a name
+    name = tf.name+imgext
+    # build cmd line
+    cmdline = ['plantuml', '-o', path, outopt, tf.name]
+
+    try:
+        logger.debug("[plantuml] About to execute "+" ".join(cmdline))
+        p = Popen(cmdline, stdout=PIPE, stderr=PIPE)
+        out, err = p.communicate()
+    except Exception as exc:
+        raise Exception('Failed to run plantuml: %s' % exc)
+    else:
+        if p.returncode == 0:
+            # diagram was correctly generated, we can remove the temporary file (if not debugging)
+            if not logger.isEnabledFor(logging.DEBUG):
+                os.remove(tf.name)
+            # renaming output image using an hash code, just to not pollute
+            # output directory with a growing number of images
+            name = os.path.join(path, os.path.basename(name))
+            newname = os.path.join(path, "%08x" % (adler32(plantuml_code.encode()) & 0xffffffff))+imgext
+
+            if os.path.exists(newname):
+                os.remove(newname)
+
+            os.rename(name, newname)
+            return 'images/' + os.path.basename(newname)
+        else:
+            # the temporary file is still available as aid understanding errors
+            raise RuntimeError('Error calling plantuml: %s' % err)

+ 89 - 0
plantuml/pandoc-plantuml

@@ -0,0 +1,89 @@
+#!/usr/bin/runhaskell
+{-|
+
+  Script adapted from pandoc-plantuml-filter by Kurt Bonne
+  Original source at https://github.com/kbonne/pandoc-plantuml-filter.git
+
+  This script is meant to be run by pandoc executed by the pandoc_reader pelican plugin.
+  I've changed output paths to be compatibile with pelican output structure.
+
+  If using the pandoc_reader pelican plugin with this script, the plantuml plugin is not necessary.
+
+  Installation:
+  -------------
+    This script requires Haskell, but if you are using pandoc, it's already installed :-)
+    Copy this file in your pelican project, in the same directory of pelicanconf.py, and make sure it is executable.
+
+    In the pelicanconf.py configure the need plugins:
+
+      PLUGINS = ['pandoc_reader']
+      PANDOC_ARGS = ['--filter=pandoc-plantuml']
+
+    If this script will be putted in a different location, adapt the PANDOC_ARGS value.
+
+  Usage:
+  ------
+    In Markdown posts use the following syntax to include PlantUML diagrams:
+
+    ```plantuml
+    @startuml
+       Alice -> Bob: Authentication Request
+       Bob --> Alice: Authentication Response
+
+       Alice -> Bob: Another authentication Request
+       Alice <-- Bob: another authentication Response
+    @enduml
+    ```
+
+    Rendered images will bu put in the output/images folder.
+-}
+
+import Text.Pandoc.JSON
+import Data.ByteString.Lazy (hGetContents, hPut)
+import Data.ByteString.Lazy.UTF8 (fromString)
+import Data.Digest.Pure.SHA (sha1, showDigest)
+import System.IO (hClose, hPutStr, IOMode(..), openBinaryFile, hPutStrLn, stderr)
+import System.Process
+import System.Directory
+
+processBlocks :: Block -> IO Block
+processBlocks b =
+  case b of
+    CodeBlock (_ , ["plantuml"], _) content -> plantUMLToImg content
+    _ -> return b
+
+plantUMLToImg :: String -> IO Block
+plantUMLToImg content =  do
+  path <- renderImage content
+  
+  --hPutStrLn stderr "dopo renderImage"
+
+  return $ Para [Image [] (path, "")]
+
+renderImage :: String -> IO String
+renderImage content = do
+  createDirectoryIfMissing (True) "output/images"
+  let path = uniqueName content ++ ".png"
+  (Just hIn, Just hOut, _, _) <-
+    createProcess (proc "plantuml" ["-pipe", "-tepg"]){ std_in = CreatePipe,
+                                                        std_out = CreatePipe }
+  hPutStr hIn content
+  hClose hIn
+
+  let outPath = "output/images/" ++ path
+  hFile <- openBinaryFile outPath WriteMode
+  img <- hGetContents hOut
+  hPut hFile img
+
+  hClose hFile
+  hClose hOut
+
+  let imgPath = "images/" ++ path
+
+  return imgPath
+
+uniqueName :: String -> String
+uniqueName = showDigest . sha1 . fromString
+
+main :: IO ()
+main = toJSONFilter processBlocks

+ 95 - 0
plantuml/plantuml_md.py

@@ -0,0 +1,95 @@
+#!/usr/bin/env python
+"""
+   PlantUML_ Extension for Python-Markdown_
+   ========================================
+
+   Syntax:
+
+       ::uml:: [format="png|svg"] [classes="class1 class2 ..."] [alt="text for alt"]
+          PlantUML script diagram
+       ::end-uml::
+
+   Example:
+
+       ::uml:: format="png" classes="uml myDiagram" alt="My super diagram"
+          Goofy ->  MickeyMouse: calls
+          Goofy <-- MickeyMouse: responds
+       ::end-uml::
+
+   Options are optional, but if present must be specified in the order format, classes, alt.
+   The option value may be enclosed in single or double quotes.
+
+.. _Python-Markdown: http://pythonhosted.org/Markdown/
+.. _PlantUML: http://plantuml.sourceforge.net/
+"""
+import os
+import re
+import markdown
+from markdown.util import etree
+from .generateUmlDiagram import generate_uml_image
+
+# For details see https://pythonhosted.org/Markdown/extensions/api.html#blockparser
+class PlantUMLBlockProcessor(markdown.blockprocessors.BlockProcessor):
+    # Regular expression inspired by the codehilite Markdown plugin
+    RE = re.compile(r'''::uml::
+                        \s*(format=(?P<quot>"|')(?P<format>\w+)(?P=quot))?
+                        \s*(classes=(?P<quot1>"|')(?P<classes>[\w\s]+)(?P=quot1))?
+                        \s*(alt=(?P<quot2>"|')(?P<alt>[\w\s"']+)(?P=quot2))?
+                    ''', re.VERBOSE)
+    # Regular expression for identify end of UML script
+    RE_END = re.compile(r'::end-uml::\s*$')
+
+    def test(self, parent, block):
+        return self.RE.search(block)
+
+    def run(self, parent, blocks):
+        block = blocks.pop(0)
+        text = block
+
+        # Parse configuration params
+        m = self.RE.search(block)
+        format  = m.group('format')  if m.group('format')  else self.config['format']
+        classes = m.group('classes') if m.group('classes') else self.config['classes']
+        alt     = m.group('alt')     if m.group('alt')     else self.config['alt']
+
+        # Read blocks until end marker found
+        while blocks and not self.RE_END.search(block):
+            block = blocks.pop(0)
+            text = text + '\n' + block
+        else:
+            if not blocks:
+                raise RuntimeError("[plantuml] UML block not closed, text is:\n"+text)
+
+        # Remove block header and footer
+        text = re.sub(self.RE, "", re.sub(self.RE_END, "", text))
+
+        path = os.path.abspath(os.path.join('output', 'images'))
+        if not os.path.exists(path):
+            os.makedirs(path)
+
+        # Generate image from PlantUML script
+        imageurl = self.config['siteurl']+'/'+generate_uml_image(path, text, format)
+        # Create image tag and append to the document
+        etree.SubElement(parent, "img", src=imageurl, alt=alt, classes=classes)
+
+
+# For details see https://pythonhosted.org/Markdown/extensions/api.html#extendmarkdown
+class PlantUMLMarkdownExtension(markdown.Extension):
+    # For details see https://pythonhosted.org/Markdown/extensions/api.html#configsettings
+    def __init__(self, *args, **kwargs):
+        self.config = {
+            'classes': ["uml","Space separated list of classes for the generated image. Default uml."],
+            'alt'    : ["uml diagram", "Text to show when image is not available."],
+            'format' : ["png", "Format of image to generate (png or svg). Default png."],
+            'siteurl': ["", "URL of document, used as a prefix for the image diagram."]
+        }
+
+        super(PlantUMLMarkdownExtension, self).__init__(*args, **kwargs)
+
+    def extendMarkdown(self, md, md_globals):
+        blockprocessor = PlantUMLBlockProcessor(md.parser)
+        blockprocessor.config = self.getConfigs()
+        md.parser.blockprocessors.add('plantuml', blockprocessor, '>code')
+
+def makeExtension(**kwargs):
+    return PlantUMLMarkdownExtension(**kwargs)

+ 41 - 63
plantuml/plantuml_rst.py

@@ -6,24 +6,25 @@
 .. _plantuml: http://plantuml.sourceforge.net/
 """
 
+import sys
 import os
-import tempfile
-from zlib import adler32
-from subprocess import Popen, PIPE
 
 from docutils.nodes import image, literal_block
 from docutils.parsers.rst import Directive, directives
-from docutils import utils, nodes
+from pelican import signals, logger
 
-from pelican import logger, signals
+from .generateUmlDiagram import generate_uml_image
 
-global_siteurl = ""
 
-class PlantUML(Directive):
+global_siteurl = "" # URL of the site, filled on plugin initialization
+
+
+class PlantUML_rst(Directive):
+    """ reST directive for PlantUML """
     required_arguments = 0
     optional_arguments = 0
     has_content = True
-    
+
     global global_siteurl
 
     option_spec = {
@@ -33,80 +34,57 @@ class PlantUML(Directive):
     }
 
     def run(self):
-	source = self.state_machine.input_lines.source(self.lineno - self.state_machine.input_offset - 1)
-	source_dir = os.path.dirname(os.path.abspath(source))
-	source_dir = utils.relative_path(None, source_dir)
-
         path = os.path.abspath(os.path.join('output', 'images'))
         if not os.path.exists(path):
             os.makedirs(path)
 
         nodes = []
-
         body = '\n'.join(self.content)
-        tf = tempfile.NamedTemporaryFile(delete=True)
-        tf.write('@startuml\n')
-        tf.write(body.encode('utf8'))
-        tf.write('\n@enduml')
-        tf.flush()
-        
-        imgformat = self.options.get('format', 'png')
-        
-        if imgformat == 'png':
-            imgext = ".png"
-            outopt = "-tpng"
-        elif imgformat == 'svg':
-            imgext = ".svg"
-            outopt = "-tsvg"
-        else:
-	    logger.error("Bad uml image format: "+imgformat)
-
-        # make a name
-        name =  tf.name+imgext
-
-        alt = self.options.get('alt', 'uml diagram')
-        classes = self.options.pop('class', ['uml'])
-        cmdline = ['plantuml', '-o', path, outopt, tf.name ]
 
         try:
-            p = Popen(cmdline, stdout=PIPE, stderr=PIPE)
-            out, err = p.communicate()
-        except Exception, exc:
+            url = global_siteurl+'/'+generate_uml_image(path, body, "png")
+        except Exception as exc:
             error = self.state_machine.reporter.error(
-                'Failed to run plantuml: %s' % (exc, ),
+                'Failed to run plantuml: %s' % exc,
                 literal_block(self.block_text, self.block_text),
                 line=self.lineno)
             nodes.append(error)
         else:
-            if p.returncode == 0:
-	        # renaming output image using an hash code, just to not pullate 
-	        # output directory with a growing number of images
-                name = os.path.join(path, os.path.basename(name))
-	        newname = os.path.join(path, "%08x" % (adler32(body) & 0xffffffff))+imgext
-	        
-	        try: # for Windows
-		    os.remove(newname)  
-		except Exception, exc:
-		    logger.debug('File '+newname+' does not exist, not deleted')
-		
-	        os.rename(name, newname)
-                url = global_siteurl + '/images/' + os.path.basename(newname)
-                imgnode = image(uri=url, classes=classes, alt=alt)
-                nodes.append(imgnode)
-            else:
-                error = self.state_machine.reporter.error(
-                    'Error in "%s" directive: %s' % (self.name, err),
-                    literal_block(self.block_text, self.block_text),
-                    line=self.lineno)
-                nodes.append(error)
+            alt = self.options.get('alt', 'uml diagram')
+            classes = self.options.pop('class', ['uml'])
+            imgnode = image(uri=url, classes=classes, alt=alt)
+            nodes.append(imgnode)
 
         return nodes
 
+
 def custom_url(generator, metadata):
+    """ Saves globally the value of SITEURL configuration parameter """
     global global_siteurl
     global_siteurl = generator.settings['SITEURL']
-    
+
+
+def pelican_init(pelicanobj):
+    """ Prepare configurations for the MD plugin """
+    try:
+        import markdown
+        from plantuml_md import PlantUMLMarkdownExtension
+    except:
+        # Markdown not available
+        logger.debug("[plantuml] Markdown support not available")
+        return
+
+    # Register the Markdown plugin
+    config = { 'siteurl': pelicanobj.settings['SITEURL'] }
+
+    try:
+        pelicanobj.settings['MD_EXTENSIONS'].append(PlantUMLMarkdownExtension(config))
+    except:
+        logger.error("[plantuml] Unable to configure plantuml markdown extension")
+
+
 def register():
     """Plugin registration."""
+    signals.initialized.connect(pelican_init)
     signals.article_generator_context.connect(custom_url)
-    directives.register_directive('uml', PlantUML)
+    directives.register_directive('uml', PlantUML_rst)