10 Jan 2013 ralsina   » (Master)

Adding Support for a Markup to Nikola

One of the goals for Nikola, my static site/blog generator is that it should be easy to extend. For example, today I added support for two markups: textile and CreoleWiki.

Since Nikola already supported HTML, reStructuredText and Markdown, adding a couple more is not very difficult. Here's how:

  1. Create a .plugin file like this one:
Name = textile
Module = compile_textile

Author = Roberto Alsina
Version = 0.1
Website = http://nikola.ralsina.com.ar
Description = Compile Textile into HTML

Then you need to create a python module called (in this case) compile_textile.py

That file is boilerplate plus two methods, compile_html and create_post

The compile_html method takes two arguments, one file from which it reads the markup, and one to write HTML. Example:

def compile_html(self, source, dest):
    if textile is None:
        raise Exception('To build this site, you need to install the "textile" package.')
    with codecs.open(dest, "w+", "utf8") as out_file:
        with codecs.open(source, "r", "utf8") as in_file:
            data = in_file.read()
        output = textile(data, head_offset=1)

Make sure to use utf8 everyhere.

The create_post function is used to create a new, empty, post with some metadata in it. Example:

def create_post(self, path, onefile=False, title="", slug="", date="", tags=""):
    with codecs.open(path, "wb+", "utf8") as fd:
        if onefile:
            fd.write('<notextile>  <!--\n')
            fd.write('.. title: %s\n' % title)
            fd.write('.. slug: %s\n' % slug)
            fd.write('.. date: %s\n' % date)
            fd.write('.. tags: %s\n' % tags)
            fd.write('.. link: \n')
            fd.write('.. description: \n')
        fd.write("\nWrite your post here.")

The metadata has to be in the form ".. fieldname: fieldvalue" and usually needs to be wrapped in a comment so that it's not shown in the output.

The onefile parameter means you have to write that metadata in the post. If it's False, you don't.

In some rare cases (Creole, I am looking at you) comments are not supported and you should raise an exception if onefile is True.

And that's it, markup support is fairly easy to add as long as there is a python implementation of a function to convert markup into html.

Syndicated 2013-01-10 17:24:21 from Lateral Opinion

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!