package Text::VimColor; use warnings; use strict; use IO::File; use File::Copy; use File::Temp qw( tempfile ); use Path::Class qw( file ); use Carp; our $SHARED = file($INC{file('Text', 'VimColor.pm')}) ->dir->subdir('VimColor')->stringify; our $VERSION = 0.09; our $VIM_COMMAND = 'vim'; our @VIM_OPTIONS = (qw( -RXZ -i NONE -u NONE -N ), "+set nomodeline"); our $NAMESPACE_ID = 'http://ns.laxan.com/text-vimcolor/1'; our %VIM_LET = ( perl_include_pod => 1, 'b:is_bash' => 1, ); our %SYNTAX_TYPE = ( Comment => 1, Constant => 1, Identifier => 1, Statement => 1, PreProc => 1, Type => 1, Special => 1, Underlined => 1, Error => 1, Todo => 1, ); # Set to true to print the command line used to run Vim. our $DEBUG = 0; sub new { my ($class, %options) = @_; $options{vim_command} = $VIM_COMMAND unless defined $options{vim_command}; $options{vim_options} = \@VIM_OPTIONS unless defined $options{vim_options}; $options{html_inline_stylesheet} = 1 unless exists $options{html_inline_stylesheet}; $options{xml_root_element} = 1 unless exists $options{xml_root_element}; $options{vim_let} = { %VIM_LET, (exists $options{vim_let} ? %{$options{vim_let}} : ()), }; croak "only one of the 'file' or 'string' options should be used" if defined $options{file} && defined $options{string}; my $self = bless \%options, $class; $self->_do_markup if defined $options{file} || defined $options{string}; return $self; } sub vim_let { my ($self, %option) = @_; while (my ($name, $value) = each %option) { $self->{vim_let}->{$name} = $value; } return $self; } sub syntax_mark_file { my ($self, $file) = @_; local $self->{file} = $file; $self->_do_markup; return $self; } sub syntax_mark_string { my ($self, $string) = @_; local $self->{string} = $string; $self->_do_markup; return $self; } sub html { my ($self) = @_; my $syntax = $self->marked; my $html = ''; $html .= $self->_html_header if $self->{html_full_page}; foreach (@$syntax) { $html .= _xml_escape($_->[1]), next if $_->[0] eq ''; $html .= "[0]\">" . _xml_escape($_->[1]) . ''; } $html .= "\n\n \n\n" if $self->{html_full_page}; return $html; } sub xml { my ($self) = @_; my $syntax = $self->marked; my $xml = ''; if ($self->{xml_root_element}) { my $filename = $self->input_filename; $xml .= "[1]), next if $_->[0] eq ''; $xml .= "[0]>" . _xml_escape($_->[1]) . "[0]>"; } $xml .= "\n" if $self->{xml_root_element}; return $xml; } sub marked { my ($self) = @_; exists $self->{syntax} or croak "an input file or string must be specified, either to 'new' or". " 'syntax_mark_file/string'"; return $self->{syntax}; } sub input_filename { my ($self) = @_; my $file = $self->{file}; return $file if defined $file && !ref $file; return undef; } # Return a string consisting of the start of an XHTML file, with a stylesheet # either included inline or referenced with a . sub _html_header { my ($self) = @_; my $input_filename = $self->input_filename; my $title = defined $self->{html_title} ? _xml_escape($self->{html_title}) : defined $input_filename ? _xml_escape($input_filename) : '[untitled]'; my $stylesheet; if ($self->{html_inline_stylesheet}) { $stylesheet = "\n"; } else { $stylesheet = "{html_stylesheet_url} || "file://$SHARED/light.css") . "\" />\n"; } "\n" . "\n" . " \n" . " $title\n" . " $stylesheet" . " \n" . " \n\n" . "
";
}

# Return a string safe to put in XML text or attribute values.  It doesn't
# escape single quotes (') because we don't use those to quote
# attribute values.
sub _xml_escape
{
   my ($s) = @_;
   $s =~ s/&/&/g;
   $s =~ s//>/g;
   $s =~ s/"/"/g;
   return $s;
}

# Actually run Vim and turn the script's output into a datastructure.
sub _do_markup
{
   my ($self) = @_;
   my $vim_syntax_script = file($SHARED, 'mark.vim')->stringify;

   die "Text::VimColor: syntax script '$vim_syntax_script' not installed.\n"
      unless -f $vim_syntax_script && -r $vim_syntax_script;

   my $filename = $self->{file};
   my $input_is_temporary = 0;
   if (ref $self->{file}) {
      my $fh;
      ($fh, $filename) = tempfile();
      $input_is_temporary = 1;

      binmode $self->{file};
      binmode $fh;
      copy($self->{file}, $fh);
   }
   elsif (exists $self->{string}) {
      my $fh;
      ($fh, $filename) = tempfile();
      $input_is_temporary = 1;

      binmode $fh;
      print $fh (ref $self->{string} ? ${$self->{string}} : $self->{string});
   }
   else {
      croak "input file '$filename' not found"
         unless -f $filename;
      croak "input file '$filename' not accessible"
         unless -r $filename;
   }

   # Create a temp file to put the output in.
   my ($out_fh, $out_filename) = tempfile();

   # Create a temp file for the 'script', which is given to vim
   # with the -s option.  This is necessary because it tells Vim not
   # to delay for 2 seconds after displaying a message.
   my ($script_fh, $script_filename) = tempfile();
   my $filetype = $self->{filetype};
   my $filetype_set = defined $filetype ? ":set filetype=$filetype" : '';
   my $vim_let = $self->{vim_let};
   print $script_fh (map { ":let $_=$vim_let->{$_}\n" }
                     grep { defined $vim_let->{$_} }
                     keys %$vim_let),
                    ":filetype on\n",
                    "$filetype_set\n",
                    ":source $vim_syntax_script\n",
                    ":write! $out_filename\n",
                    ":qall!\n";
   close $script_fh;

   $self->_run(
      $self->{vim_command},
      @{$self->{vim_options}},
      $filename,
      '-s', $script_filename,
   );

   unlink $filename
      if $input_is_temporary;
   unlink $out_filename;
   unlink $script_filename;

   my $data = do { local $/; <$out_fh> };

   # Convert line endings to Unix ones.
   $data =~ s/\x0D\x0A?/\n/g;

   my $syntax = [];
   LOOP: {
      _add_markup($syntax, $1, $2), redo LOOP
         if $data =~ /\G>(.*?)>(.*?)<\1]+)/cgs;
   }

   $self->{syntax} = $syntax;
}

# Given an array ref ($syntax), we add a new syntax chunk to it, unescaping
# the text and making sure that consecutive chunks of the same type are
# merged.
sub _add_markup
{
   my ($syntax, $type, $text) = @_;

   # Ignore types we don't know about.  At least one syntax file (xml.vim)
   # can produce these.  It happens when a syntax type isn't 'linked' to
   # one of the predefined types.
   $type = ''
      unless exists $SYNTAX_TYPE{$type};

   # Unescape ampersands and pointies.
   $text =~ s/&l//g;
   $text =~ s/&a/&/g;

   if (@$syntax && $syntax->[-1][0] eq $type) {
      # Concatenate consecutive bits of the same type.
      $syntax->[-1][1] .= $text;
   }
   else {
      # A new chunk of marked-up text.
      push @$syntax, [ $type, $text ];
   }
}

# This is a private internal method which runs a program.
# It takes a list of the program name and arguments.
sub _run
{
   my ($self, $prog, @args) = @_;

   if ($DEBUG) {
      print STDERR __PACKAGE__."::_run: $prog " .
            join(' ', map { s/'/'\\''/g; "'$_'" } @args) . "\n";
   }

   my $pid = fork;
   if ($pid) {
      waitpid($pid, 0);
      my $error = $? >> 8;
      die "$0: $prog returned an error code of '$error'.\n" if $error;
   }
   else {
      defined $pid
         or die "$0: error forking to run $prog: $!\n";
      open STDIN, '/dev/null';
      open STDOUT, '>/dev/null';
      open STDERR, '>/dev/null';
      exec($prog, @args);
      die "$0: error execing $prog: $!\n";
   }
}

1;

__END__

=head1 NAME

Text::VimColor - syntax color text in HTML or XML using Vim

=head1 SYNOPSIS

   use Text::VimColor;
   my $syntax = Text::VimColor->new(
      file => $0,
      filetype => 'perl',
   );

   print $syntax->html;
   print $syntax->xml;

=head1 DESCRIPTION

This module tries to markup text files according to their syntax.  It can
be used to produce web pages with pretty-printed colourful source code
samples.  It can produce output in the following formats:

=over 4

=item HTML

Valid XHTML 1.0, with the exact colouring and style left to a CSS stylesheet

=item XML

Pieces of text are marked with XML elements in a simple vocabulary,
which can be converted to other formats, for example, using XSLT

=item Perl array

A simple Perl data structure, so that Perl code can be used to turn it
into whatever is needed

=back

This module works by running the Vim text editor and getting it to apply its
excellent syntax highlighting (aka 'font-locking') to an input file, and mark
pieces of text according to whether it thinks they are comments, keywords,
strings, etc.  The Perl code then reads back this markup and converts it
to the desired output format.

This is an object-oriented module.  To use it, create an object with
the C function (as shown above in the SYNOPSIS) and then call methods
to get the markup out.

=head1 METHODS

=over 4

=item new(I)

Returns a syntax highlighting object.  Pass it a hash of options.

The following options are recognised:

=over 4

=item file

The file to syntax highlight.  Can be either a filename or an open file handle.

Note that using a filename might allow Vim to guess the file type from its
name if none is specified explicitly.

If the file isn't specified while creating the object, it can be given later
in a call to the C method (see below), allowing a single
Text::VimColor object to be used with multiple input files.

=item string

Use this to pass a string to be used as the input.  This is an alternative
to the C option.  A reference to a string will also work.

The C method (see below) is another way to use a string
as input.

=item filetype

Specify the type of file Vim should expect, in case Vim's automatic
detection by filename or contents doesn't get it right.  This is
particularly important when providing the file as a string of file
handle, since Vim won't be able to use the file extension to guess
the file type.

The filetypes recognised by Vim are short strings like 'perl' or 'lisp'.
They are the names of files in the 'syntax' directory in the Vim
distribution.

=item html_full_page

By default the C output method returns a fragment of HTML, not a
full file.  To make useful output this must be wrapped in a CpreE>
element and a stylesheet must be included from somewhere.  Setting the
C option will instead make the C method return a
complete stand-alone HTML file.

Note that while this is useful for testing, most of the time you'll want to
put the syntax highlighted source code in a page with some other content,
in which case the default output of the C method is more appropriate.

=item html_inline_stylesheet

Turned on by default, but has no effect unless C is also
enabled.

This causes the CSS stylesheet defining the colours to be used
to render the markup to be be included in the HTML output, in a
CstyleE> element.  Turn it off to instead use a ClinkE>
to reference an external stylesheet (recommended if putting more than one
page on the web).

=item html_stylesheet

Ignored unless C and C are both
enabled.

This can be set to a stylesheet to include inline in the HTML output (the
actual CSS, not the filename of it).

=item html_stylesheet_file

Ignored unless C and C are both
enabled.

This can be the filename of a stylesheet to copy into the HTML output,
or a file handle to read one from.  If neither this nor C
are given, the supplied stylesheet F will be used instead.

=item html_stylesheet_url

Ignored unless C is enabled and C
is disabled.

This can be used to supply the URL (relative or absolute) or the stylesheet
to be referenced from the HTML ClinkE> element in the header.
If this isn't given it will default to using a C URL to reference
the supplied F stylesheet, which is only really useful for testing.

=item xml_root_element

By default this is true.  If set to a false value, XML output will not be
wrapped in a root element called , but will be otherwise the
same.  This could allow XML output for several files to be concatenated,
but to make it valid XML a root element must be added.  Disabling this
option will also remove the binding of the namespace prefix C, so
an C attribute would have to be added elsewhere.

=item vim_command

The name of the executable which will be run to invoke Vim.
The default is C.

=item vim_options

A reference to an array of options to pass to Vim.  The default options are:

   qw( -RXZ -i NONE -u NONE -N )

=item vim_let

A reference to a hash of options to set in Vim before the syntax file
is loaded.  Each of these is set using the C<:let> command to the value
specified.  No escaping is done on the values, they are executed exactly
as specified.

Values in this hash override some default options.  Use a value of
C to prevent a default option from being set at all.  The
defaults are as follows:

   (
      perl_include_pod => 1,     # Recognize POD inside Perl code
      'b:is_bash' => 1,          # Allow Bash syntax in shell scripts
   )

These settings can be modified later with the C method.

=back

=item vim_let(I =E I, ...)

Change the options that are set with the Vim C command when Vim
is run.  See C for details.

=item syntax_mark_file(I)

Mark up the specified file.  Subsequent calls to the output methods will then
return the markup.  It is not necessary to call this if a C or C
option was passed to C.

Returns the object it was called on, so an output method can be called
on it directly:

   my $syntax = Text::VimColor->new(
      vim_command => '/usr/local/bin/special-vim',
   );

   foreach (@files) {
      print $syntax->syntax_mark_file($_)->html;
   }

=item syntax_mark_string(I)

Does the same as C (see above) but uses a string as input.
I can also be a reference to a string.
Returns the object it was called on.

=item html()

Return XHTML markup based on the Vim syntax colouring of the input file.

Unless the C option is set, this will only return a fragment
of HTML, which can then be incorporated into a full page.  The fragment
will be valid as either HTML and XHTML.

The only markup used for the actual text will be CspanE> elements
wrapped round appropriate pieces of text.  Each one will have a C
attribute set to a name which can be tied to a foreground and background
color in a stylesheet.  The class names used will have the prefix C,
for example C.  For the full list see the section
HIGHLIGHTING TYPES below.

=item xml()

Returns markup in a simple XML vocabulary.  Unless the C
option is turned off (it's on by default) this will produce a complete XML
document, with all the markup inside a CsyntaxE> element.

This XML output can be transformed into other formats, either using programs
which read it with an XML parser, or using XSLT.  See the
text-highlight-vim(1) program for an example of how XSLT can be used with
XSL-FO to turn this into PDF.

The markup will consist of mixed content with elements wrapping pieces
of text which Vim recognized as being of a particular type.  The names of
the elements used are the ones listed in the HIGHLIGHTING TYPES section
below.

The CsyntaxE> element will declare the namespace for all the
elements prodeced, which will be C.
It will also have an attribute called C, which will be set to the
value returned by the C method, if that returns something
other than undef.

The XML namespace is also available as C<$Text::VimColor::NAMESPACE_ID>.

=item marked()

This output function returns the marked-up text in the format which the module
stores it in internally.  The data looks like this:

   use Data::Dumper;
   print Dumper($syntax->marked);

   $VAR1 = [
      [ 'Statement', 'my' ],
      [ '', ' ' ],
      [ 'Identifier', '$syntax' ],
      [ '', ' = ' ],
       ...
   ];

The C method returns a reference to an array.  Each item in the
array is itself a reference to an array of two items: the first is one of
the names listed in the HIGHLIGHTING TYPES section below (or the empty
string if none apply), and the second is the actual piece of text.

=item input_filename()

Returns the filename of the input file, or undef if a filename wasn't
specified.

=back

=head1 HIGHLIGHTING TYPES

The following list gives the names of highlighting types which will be
set for pieces of text.  For HTML output, these will appear as CSS class
names, except that they will all have the prefix C added.  For XML
output, these will be the names of elements which will all be in the
namespace C.

Here is the complete list:

=over 4

=item *

Comment

=item *

Constant

=item *

Identifier

=item *

Statement

=item *

PreProc

=item *

Type

=item *

Special

=item *

Underlined

=item *

Error

=item *

Todo

=back

=head1 SEE ALSO

=over 4

=item text-highlight-vim(1)

A simple command line interface to this module's features.  It can be used
to produce HTML and XML output, and can also generate PDF output using
an XSLT/XSL-FO stylesheet and the FOP processor.

=item http://www.vim.org/

Everything to do with the Vim text editor.

=item http://ungwe.org/blog/

The author's weblog, which uses this module.  It is used to make the code
samples look pretty.

=back

=head1 BUGS

Quite a few, actually:

=over 4

=item *

Apparently this module doesn't always work if run from within a 'gvim'
window, although I've been unable to reproduce this so far.
CPAN bug #11555.

=item *

Things can break if there is already a Vim swapfile, but sometimes it
seems to work.

=item *

If Vim returns an exit code, it should be interpreted and a human-readable
error message given.

=item *

There should be a way of getting a DOM object back instead of an XML string.

=item *

It should be possible to choose between HTML and XHTML, and perhaps there
should be some control over the DOCTYPE declaration when a complete file is
produced.

=item *

With Vim versions earlier than 6.2 there is a 2 second delay each time
Vim is run.

=item *

It doesn't work on Windows.  I am unlikely to fix this, but if anyone
who knows Windows can sort it out let me know.

=item *

I should think about whether to add control characters other than
tab to the C setting.  Would that do any harm?  If not,
I might as well avoid Vim fiddling with those characters.

=back

=head1 AUTHOR

Geoff Richards Eqef@laxan.comE

The Vim script F is a crufted version of F<2html.vim> by
Bram Moolenaar EBram@vim.orgE and
David Ne\v{c}as (Yeti) Eyeti@physics.muni.czE.

=head1 COPYRIGHT

Copyright 2002-2005, Geoff Richards.

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

=cut

# Local Variables:
# mode: perl
# perl-indent-level: 3
# perl-continued-statement-offset: 3
# End:
# vi:ts=3 sw=3 expandtab: