File: HTML.pm

package info (click to toggle)
freej 0.10git20080824-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 13,504 kB
  • ctags: 19,398
  • sloc: ansic: 135,255; cpp: 32,550; sh: 9,318; perl: 2,932; asm: 2,355; yacc: 1,178; makefile: 1,119; java: 136; lex: 94; python: 16
file content (95 lines) | stat: -rw-r--r-- 2,120 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package JavaScript::Syntax::HTML;

=head1 NAME

JavaScript::Syntax::HTML - Convert JavaScript sourcecode to HTML

=head1 SYNOPSIS

    use JavaScript::Syntax::HTML qw(to_html to_html_document);
    my $html_fragment = to_html($js_src);
    my $html_doc = output_html_document($js_src);

=head1 DESCRIPTION

JavaScript::Syntax::HTML processes JavaScript code and outputs HTML with
all reserved words marked up. 

The to_html method only outputs an HTML fragment (no <body> or <html> tags),
and only marks up the reserved words with CSS styles.

The to_html_document method outputs a full HTML document, and does include
style information for the reserved words markup.

The style classes that can be defined for use with to_html are C<comment>, 
C<literal>, and C<reserved>.

=head1 AUTHOR

Gabriel Reid gab_reid@users.sourceforge.net

=cut

use warnings;
use strict;
use Exporter;

our @ISA = qw(Exporter);
our @EXPORT_OK = qw(to_html to_html_document);

sub to_html {
    local $_ = shift;
    s/\&/&amp;/g;
    s/</&lt;/g;
    s/>/&gt;/g;
    s/
        ((?:\/\*.*?\*\/)
        |
        (?:\/\/[^\n]*$))
        |
        ('[^']*'|"[^"]*")
        |
        \b(function|for|if|while|return|else|prototype|this)\b
        / get_substitution($1, $2, $3) /egsxm; 
    $_;
}

sub get_substitution {
    my ($comment, $stringliteral, $resword) = @_;
    my $content;
    if ($comment){
        $comment =~ s/(\@\w+)\b/get_span('attrib', $1)/eg;
        return get_span('comment', $comment);
    } elsif ($stringliteral){
        return get_span('literal', $stringliteral);
    } elsif ($resword){
        return get_span('reserved', $resword);
    }
}

sub get_span {
    my ($class, $inner) = @_;
    qq(<span class="$class">$inner</span>);
}

sub to_html_document {
    my ($src) = @_;
    $src = &to_html($src);
    qq(
<html>
    <head>
	<style>
            body { background: #FFFFFF }
	    .reserved { color: #DD3333 }
            .comment { color: #339933 }
            .attrib { color: #FF0000 }
            .literal { color: #5555FF }
	</style>
    </head>
    <body>
	<pre>
$src
	</pre>
    </body>
</html>);
}