Text::MediawikiFormat(3) Translate Wiki markup into other text formats

VERSION

Version 1.04

SYNOPSIS


use Text::MediawikiFormat 'wikiformat';
my $html = wikiformat ($raw);
my $text = wikiformat ($raw, {}, {implicit_links => 1});

DESCRIPTION

<http://wikipedia.org> and its sister projects use the PHP Mediawiki to format their pages. This module attempts to duplicate the Mediawiki formatting rules. Those formatting rules can be simple and easy to use, while providing more advanced options for the power user. They are also easy to translate into other, more complicated markup languages with this module. It creates HTML by default, but could produce valid POD, DocBook, XML, or any other format imaginable.

The most important function is "Text::MediawikiFormat::format()". It is not exported by default, but will be exported as "wikiformat()" if any options at all are passed to the exporter, unless the name is overridden explicitly. See ``EXPORT'' for more information.

It should be noted that this module is written as a drop in replacement for Text::WikiMarkup that expands on that modules functionality and provides a default rule set that may be used to format text like the PHP Mediawiki. It is also well to note early that if you just want a Mediawiki clone (you don't need to customize it heavily and you want integration with a back end database), you should look at Wiki::Toolkit::Formatter::Mediawiki.

FUNCTIONS

format

"format()" takes one required argument, the text to convert, and returns the converted text. It allows two optional arguments. The first is a reference to a hash of tags used to override the function's default behavior. Anything passed in here will override the default tags. The second argument is a hash reference of options. The options are currently:
prefix
The prefix of any links to wiki pages. In HTML mode, this is the path to the Wiki. The actual linked item itself will be appended to the prefix. This is useful to create full URIs:

    {prefix => 'http://example.com/wiki.pl?page='}

extended
A boolean flag, true by default, to let square brackets mark links. An optional title may occur after the Wiki targets, preceded by an open pipe. URI titles are separated from their title with a space. These are valid extended links:

    [[A wiki page|and the title to display]]
    [http://ximbiot.com URI title]

Where the linking semantics of the destination format allow it, the result will display the title instead of the URI. In HTML terms, the title is the content of an "A" element (not the content of its "HREF" attribute).

You can use delimiters other than single square brackets for marking extended links by passing a value for "extended_link_delimiters" in the %tags hash when calling "format".

Note that if you disable this flag, you should probably enable "implicit_links" or there will be no automated way to link to other pages in your wiki.

implicit_links
A boolean flag, false by default, to create links from StudlyCapsStrings.
absolute_links
A boolean flag, true by default, which treats any links that are absolute URIs (such as "http://www.cpan.org/") specially. Any prefix will not apply. This should maybe be called implicit_absolute_links since the "extended" option enables absolute links inside square brackets by default.

A link is any text that starts with a known schema followed by a colon and one or more non-whitespace characters. This is a distinct subset of what URI recognizes as a URI, but is a good first-order approximation. If you need to recognize more complex URIs, use the standard wiki formatting explained earlier.

The recognized schemas are those defined in the "schema" value in the %tags hash. "schema" defaults to "http", "https", "ftp", "mailto", and "gopher".

process_html
This flag, true by default, causes the formatter to ignore block level wiki markup (code, ordered, unordered, etc...) when they occur on lines which also contain allowed block-level HTML tags (<pre>, <ol>, <ul>, </pre>, etc...). Phrase level wiki markup (emphasis, strong, & links) is unaffected by this flag.

format_line

        $formatted = format_line ($raw, $tags, $opts);

This function is never exported. It formats the phrase elements of a single line of text (emphasised, strong, and links).

This is only meant to be called from Text::MediawikiFormat::Block and so requires $tags and $opts to have all elements filled in. If you find a use for it, please let me know and maybe I will have it default the missing elements as "format()" does.

Wiki Format

Refer to <http://en.wikipedia.org/wiki/Help:Contents/Editing_Wikipedia> for description of the default wiki format, as interpreted by this module. Any discrepencies will be considered bugs in this module, with a few exceptions.

Unimplemented Wiki Markup

Templates, Magic Words, and Wanted Links
Templates, magic words, and the colorization of wanted links all require a back end data store that can be consulted on the existance and content of named pages. "Text::MediawikiFormat" has deliberately been constructed such that it operates independantly from such a back end. For an interface to "Text::MediawikiFormat" which implements these features, see Wiki::Toolkit::Formatter::Mediawiki.
Tables
This is on the TODO list.

EXPORT

If you'd like to make your life more convenient, you can optionally import a subroutine that already has default tags and options set up. This is especially handy if you use a prefix:

    use Text::MediawikiFormat prefix => 'http://www.example.com/';
    wikiformat ('some text');

Tags are interpreted as default members of the $tags hash normally passed to "format", except for the five options (see above) and the "as" key, who's value is interpreted as an alternate name for the imported function.

To use the "as" flag to control the name by which your code calls the imported function, for example,

    use Text::MediawikiFormat as => 'formatTextWithWikiStyle';
    formatTextWithWikiStyle ('some text');

You might choose a better name, though.

The calling semantics are effectively the same as those of the "format()" function. Any additional tags or options to the imported function will override the defaults. This code:

    use Text::MediawikiFormat as => 'wf', extended => 0;
    wf ('some text', {}, {extended => 1});

enables extended links, after specifying that the default behavior should be to disable them.

GORY DETAILS

Tags

There are two types of Wiki markup: phrase markup and blocks. Blocks include lists, which are made up of lines and can also contain other lists.

Phrase Markup

The are currently three types of wiki phrase markup. These are the strong and emphasized markup and links. Links may additionally be of three subtypes, extended, implicit, or absolute.

You can change the regular expressions used to find strong and emphasized tags:

    %tags = (
        strong_tag     => qr/\*([^*]+?)\*/,
        emphasized_tag => qr|/([^/]+?)/|,
    );
    $wikitext = 'this is *strong*, /emphasized/, and */em+strong/*';
    $htmltext = wikiformat ($wikitext, \%tags, {});

You can also change the regular expressions used to find links. The following just sets them to their default states (but enables parsing of implicit links, which is not the default):

    my $html = wikiformat
    (
        $raw,
        {implicit_link_delimiters => qr!\b(?:[A-Z][a-z0-9]\w*){2,}!,
         extended_link_delimiters => qr!\[(?:\[[^][]*\]|[^][]*)\]!,
        },
        {implicit_links => 1}
    );

In addition, you may set the function references that format strong and emphasized text and links. The strong and emphasized functions receive only the text to be formatted as an argument and are expected to return the formatted text. The link formatter also recieves references to the $tags and $opts arrays. For example, the following sets the strong and emphasized formatters to their default state while replacing the link formatter with one which strips href information and returns only the title text:

    my $html = wikiformat
    (
        $raw,
        {strong => sub {"<strong>$_[0]</strong>"},
         emphasized => sub {"<em>$_[0]</em>"},
         link => sub
         {
         my ($tag, $opts, $tags) = @_;
         if ($tag =~ s/^\[\[([^][]+)\]\]$/$1/)
         {
             my ($page, $title) = split qr/\|/, $tag, 2;
             return $title if $title;
             return $page;
         }
         elsif ($tag =~ s/^\[([^][]+)\]$/$1/)
         {
             my ($href, $title) = split qr/ /, $tag, 2;
             return $title if $title;
             return $href;
         }
         else
         {
             return $tag;
         }
         },
        },
    );

Blocks

The default block types are "code", "line", "paragraph", "paragraph_break", "unordered", "ordered", "definition", and "header".

Block entries in the tag hashes must contain array references. The first two items are the tags used at the start and end of the block. The third and fourth contain the tags used at the start and end of each line. Where there needs to be more processing of individual lines, use a subref as the third item. This is how the module processes ordered lines in HTML lists and headers:

    my $html = wikiformat
    (
        $raw,
        {ordered => ['<ol>', "</ol>\n", '<li>', "<li>\n"],
         header => ['', "\n", \&_make_header],
        },
    );

The first argument to these subrefs is the post-processed text of the line itself. (Processing removes the indentation and tokens used to mark this as a list and checks the rest of the line for other line formattings.) The second argument is the indentation level (see below). The subsequent arguments are captured variables in the regular expression used to find this list type. The regexp for headers is:

    $html = wikiformat
    (
        $raw,
        {blocks => {header => qr/^(=+)\s*(.+?)\s*\1$/}}
    );

The module processes indentation first, if applicable, and stores the indentation level (the length of the indentation removed).

Lists automatically start and end as necessary.

Because regular expressions could conceivably match more than one line, block level markup is processed in a specific order. The "blockorder" tag governs this order. It contains a reference to an array of the names of the appropriate blocks to process. If you add a block type, be sure to add an entry for it in "blockorder":

    my $html = wikiformat
    (
        $raw,
        {invisible => ['', '', '', ''],
         blocks => {invisible => qr!^--(.*?)--$!},
            blockorder => [qw(code header line ordered
                      unordered definition invisible
                      paragraph_break paragraph)]
               },
        },
);

Finding blocks

As has already been mentioned in passing, "Text::MediawikiFormat" uses regular expressions to find blocks. These are in the %tags hash under the "blocks" key. For example, to change the regular expression to find code block items, use:

    my $html = wikiformat ($raw, {blocks => {code => qr/^:\s+/}});

This will require a leading colon to mark code lines (note that as writted here, this would interfere with the default processing of definition lists).

Finding Blocks in the Correct Order

As intrepid bug reporter Tom Hukins pointed out in CPAN RT bug #671, the order in which "Text::MediawikiFormat" searches for blocks varies by platform and version of Perl. Because some block-finding regular expressions are more specific than others, what you intend to be one type of block may turn into a different list type.

If you're adding new block types, be aware of this. The "blockorder" entry in %tags exists to force "Text::MediawikiFormat" to apply its regexes from most specific to least specific. It contains an array reference. By default, it looks for ordered lists first, unordered lists second, and code references at the end.

SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc Text::MediawikiFormat

You can also look for information at:

AUTHOR

Derek Price "derek at ximbiot.com" is the author.

ACKNOWLEDGEMENTS

This module is derived from Text::WikiFormat, written by chromatic. chromatic's original credits are below:

chromatic, "chromatic at wgz.org", with much input from the Jellybean team (including Jonathan Paulett). Kate L Pugh has also provided several patches, many failing tests, and is usually the driving force behind new features and releases. If you think this module is worth buying me a beer, she deserves at least half of it.

Alex Vandiver added a nice patch and tests for extended links.

Tony Bowden, Tom Hukins, and Andy H. all suggested useful features that are now implemented.

Sam Vilain, Chris Winters, Paul Schmidt, and Art Henry have all found and reported silly bugs.

Blame me for the implementation.

BUGS

The link checker in "format_line()" may fail to detect existing links that do not follow HTML, XML, or SGML style. They may die with some SGML styles too. Sic transit gloria mundi.

TODO

  • Optimize "format_line()" to work on a list of lines

COPYRIGHT & LICENSE

 Copyright (c) 2006-2008 Derek R. Price, all rights reserved.
 Copyright (c) 2002 - 2006, chromatic, all rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.