# A plugin of Moveable Type to provides a source codes of the Vim color syntax.
# Original version is antipop (http://antipop.gs/mt/2005/01/02/040015) by kentaro.
package MT::Plugin::VimColor;

use strict;
use MT;
use MT::Template::Context;
use Text::VimColor 0.11;

our $VERSION = 0.51;

my $plugin;

if (MT->version_number >= 3.0) {
    eval {
	require MT::Plugin;

	$plugin = new MT::Plugin(
	    name	=> 'VimColor',
	    description	=> "Adds span markups to source codes with the Vim color syntax.",
	    version	=> $VERSION,
	    doc_link	=> 'http://blog.drry.jp/tag/Movable%20Type/Plugins/Vim',
	    author_name	=> 'drry',
	    author_link	=> 'http://blog.drry.jp/',
#	    config_template => 'vimcolor.tmpl',
#	    settings	=> MT::PluginSettings->new([
#		['filetype' => { Default => 'none' }],
#	    ]),
	);

	MT->add_plugin( $plugin );
    };
}

MT::Template::Context->add_global_filter(vim_color => \&syntax_mark);
MT::Template::Context->add_container_tag(VimColor => \&SyntaxMark);

sub syntax_mark {
    my @strings = split /(.+?<\/code><\/pre>)/s, shift;
    my $default_ft = shift;
    my $string = shift @strings;
    my @options = (qw( -RXZ -i NONE -u NONE -N ),
	'+set nomodeline',
	'+set expandtab',
	'+set encoding=' . MT::ConfigMgr->instance()->PublishCharset);
    my $vimcolor = Text::VimColor->new(vim_options => \@options);

    foreach (@strings) {
	my $filetype = s|(<pre[^>]*><code[^>]*?) class="(\w*)"([^>]*>.+?</code></pre>)|$1.$3|se ?
	    $2: $default_ft;

	unless ($filetype eq 'none') {
	    s|(<pre[^>]*?><code[^>]*?>\s*)(.+?)(\s*</code></pre>)|$1.$vimcolor->syntax_mark_string(unescape($2), filetype => $filetype)->html.$3|se;
	    s|(<span class="syn\w+">)(\s+)(</span>)|$2|sg;
	}

	$string .= $_;
    }

    return $string;
}

sub SyntaxMark {
    my ($ctx, $args, $cond) = @_;
    my $out = $ctx->stash('builder')->build($ctx, $ctx->stash('tokens'), $cond);
    syntax_mark($out, (exists $args->{filetype} ? $args->{filetype} : 'none'),
	$cond);
}

sub unescape {
    my $string = shift;

    $string =~ s/&quot;/"/g;
    $string =~ s/&lt;/</g;
    $string =~ s/&gt;/>/g;
    $string =~ s/&amp;/&/g;

    return $string;
}

1;

__END__

=head1 SYNOPSIS

Once installed in your Movable Type plugins directory, the following
new attribute will be available for use within templates:

<$MTEntryBody vim_color="perl"$>

=cut

