File: Reindent.pm

package info (click to toggle)
libxml-filter-reindent-perl 0.03-7
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, squeeze, stretch, wheezy
  • size: 88 kB
  • ctags: 16
  • sloc: perl: 194; makefile: 2
file content (309 lines) | stat: -rw-r--r-- 8,289 bytes parent folder | download | duplicates (4)
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package XML::Filter::Reindent;
use strict;
use XML::Filter::DetectWS;

use vars qw{ $VERSION @ISA };
$VERSION = '0.03';
@ISA = qw{ XML::Filter::DetectWS };

sub MAYBE (%) { 2 }

sub new
{
    my $class = shift;
    my $self = $class->SUPER::new (@_);

    # Use one space per indent level (by default)
    $self->{Tab} = " " unless defined $self->{Tab};

    # Note that this is a PerlSAX filter so we use the XML newline ("\x0A"),
    # not the Perl output newline ("\n"), by default.
    $self->{Newline} = "\x0A" unless defined $self->{Newline};

    $self;
}

# Indent the element if its parent element says so
sub indent_element
{
    my ($self, $event, $parent_says_indent) = @_;
    return $parent_says_indent;
}

# Always indent children unless element (or its ancestor) has 
# xml:space="preserve" attribute
sub indent_children
{
    my ($self, $event) = @_;
    return $event->{PreserveWS} ? 0 : MAYBE;
}

sub start_element
{
    my ($self, $event) = @_;

    my $parent = $self->{ParentStack}->[-1];
    my $level = $self->{Level}++;
    $self->SUPER::start_element ($event);

    my $parent_says_indent = $parent->{IndentChildren} ? 1 : 0;
    # init with 1 if parent says MAYBE
    $event->{Indent} = $self->indent_element ($event, $parent_says_indent) ?
			$level : undef;

    $event->{IndentChildren} = $self->indent_children ($event);
}

sub end_element
{
    my ($self, $event) = @_;
    my $start_element = $self->{ParentStack}->[-1];

    if ($start_element->{IndentChildren} == MAYBE)
    {
	my $q = $self->{EventQ};
	my $prev = $q->[-1];

	if ($prev == $start_element)
	{
	    # End tag follows start tag: compress tag
	    $start_element->{Compress} = 1;
	    $event->{Compress} = 1;
#?? could detect if it contains only ignorable_ws
	}
	elsif ($prev->{EventType} eq 'characters')
	{
	    if ($q->[-2] == $start_element)
	    {
		# Element has only one child, a text node.
		# Print element as: <a>text here</a>
		delete $prev->{Indent};
		$start_element->{IndentChildren} = 0;
	    }
	}
    }

    my $level = --$self->{Level};
    $event->{Indent} = $start_element->{IndentChildren} ? $level : undef;

    my $compress = $start_element->{Compress};
    if ($compress)
    {
	$event->{Compress} = $compress;
	delete $event->{Indent};
    }

    $self->SUPER::end_element ($event);
}

sub end_document
{
    my ($self, $event) = @_;

    $self->push_event ('end_document', $event || {});
    $self->flush (0);	# send remaining events
}

sub push_event
{
    my ($self, $type, $event) = @_;

    $event->{EventType} = $type;
    if ($type =~ /^(characters|comment|processing_instruction|entity_reference|cdata)$/)
    {
	my $indent_kids = $self->{ParentStack}->[-1]->{IndentChildren} ? 1 : 0;
	$event->{Indent} =  $indent_kids ? $self->{Level} : undef;
    }

    my $q = $self->{EventQ};
    push @$q, $event;

    $self->flush (4);	# keep 4 events on the stack (maybe 3 is enough)
}

sub flush
{
    my ($self, $keep) = @_;
    my $q = $self->{EventQ};

    my $result;

    while (@$q > $keep)
    {
	my $head = $q->[0];
#	print "head=" . $head->{EventType} . " indent=" . $head->{Indent} . "\n";

	if ($head->{EventType} =~ /ws|ignorable/)
	{
	    my $next = $q->[1];
	    my $indent = $next->{Indent};

	    if (defined $indent)	# fix existing indent
	    {
		$head->{Data} = $self->{Newline} . ($self->{Tab} x $indent);
		$result = $self->send (2);
	    }
	    else		# remove existing indent
	    {
		shift @$q;
		$result = $self->send (1);
	    }
#?? remove keys: Indent, ...
	}
	else
	{
	    my $indent = $head->{Indent};

	    if (defined $indent)	# insert indent
	    {
		unshift @$q, { EventType => 'ws', 
			       Data => $self->{Newline} . ($self->{Tab} x $indent) };
		$result = $self->send (2);
	    }
	    else		# no indent - leave as is
	    {
		$result = $self->send (1);
	    }
	}
    }
    return $result;
}

sub send
{
    my ($self, $i) = @_;
    
    my $q = $self->{EventQ};

    my $result;
    while ($i--)
    {
	my $event = shift @$q;
	my $type = $event->{EventType};
	delete $event->{EventType};

#print "TYPE=$type " . join(",", map { "$_=" . $event->{$_} } keys %$event) . "\n";
	$result = $self->{Callback}->{$type}->($event);
    }
    return $result;
}

1;	# package return code

=head1 NAME

XML::Filter::Reindent - Reformats whitespace for pretty printing XML

=head1 SYNOPSIS

 use XML::Handler::Composer;
 use XML::Filter::Reindent;

 my $composer = new XML::Handler::Composer (%OPTIONS);
 my $indent = new XML::Filter::Reindent (Handler => $composer, %OPTIONS);

=head1 DESCRIPTION

XML::Filter::Reindent is a sub class of L<XML::Filter::DetectWS>.

XML::Filter::Reindent can be used as a PerlSAX filter to reformat an
XML document before sending it to a PerlSAX handler that prints it
(like L<XML::Handler::Composer>.)

Like L<XML::Filter::DetectWS>, it detects ignorable whitespace and blocks of
whitespace characters in certain places. It uses this information and
information supplied by the user to determine where whitespace may be
modified, deleted or inserted. 
Based on the indent settings, it then modifies, inserts and deletes characters
and ignorable_whitespace events accordingly.

This is just a first stab at the implementation.
It may be buggy and may change completely!

=head1 Constructor Options

=over 4

=item * Handler

The PerlSAX handler (or filter) that will receive the PerlSAX events from this 
filter.

=item * Tab (Default: one space)

The number of spaces per indent level for elements etc. in document content.

=item * Newline (Default: "\x0A")

The newline to use when re-indenting. 
The default is the internal newline used by L<XML::Parser>, L<XML::DOM> etc.,
and should be fine when used in combination with L<XML::Handler::Composer>.

=back

=head1 $self->indent_children ($start_element_event)

This method determines whether children of a certain element
may be reformatted. 
The default implementation checks the PreserveWS parameter of the specified
start_element event and returns 0 if it is set or MAYBE otherwise.
The value MAYBE (2) indicates that further investigation is needed, e.g.
by examining the element contents. A value of 1 means yes, indent the
child nodes, no further investigation is needed.

NOTE: the PreserveWS parameter is set by the parent class, 
L<XML::Filter::DetectWS>, when the element or one of its ancestors has
the attribute xml:space="preserve".

Override this method to tweak the behavior of this class.

=head1 $self->indent_element ($start_element_event, $parent_says_indent)

This method determines whether a certain element may be re-indented. 
The default implementation returns the value of the $parent_says_indent
parameter, which was set to the value returned by indent_children for the
parent element. In other words, the element will be re-indented if the
parent element allows it.

Override this method to tweak the behavior of this class.
I'm not sure how useful this hook is. Please provide feedback!

=head1 Current Implementation

The current implementation puts all incoming Perl SAX events in a queue for
further processing. When determining which nodes should be re-indented,
it sometimes needs information from previous events, hence the use of the 
queue.

The parameter (Compress => 1) is added to 
matching start_element and end_element events with no events in between
This indicates to an XML printer that a compressed notation can be used, 
e.g <foo/>.

If an element allows reformatting of its contents (xml:space="preserve" was 
not active and indent_children returned MAYBE), the element
contents will be reformatted unless it only has one child node and that
child is a regular text node (characters event.) 
In that case, the element will be printed as <foo>text contents</foo>.

If you want element nodes with just one text child to be reindented as well,
simply override indent_children to return 1 instead of MAYBE (2.)

This behavior may be changed or extended in the future.

=head1 CAVEATS

This code is highly experimental! 
It has not been tested well and the API may change.

The code that detects blocks of whitespace at potential indent positions
may need some work.

=head1 AUTHOR

Original Author is Enno Derksen.

Send bug reports, hints, tips, suggestions to T.J. Mather at
<F<tjmather@tjmather.com>>. 

=cut