-
Notifications
You must be signed in to change notification settings - Fork 38
/
TML2HTML.pm
1623 lines (1345 loc) · 49.8 KB
/
TML2HTML.pm
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# See bottom of file for license and copyright information
=pod
---+ package Foswiki::Plugins::WysiwygPlugin::TML2HTML
Convertor class for translating TML (Topic Meta Language) into
HTML
The convertor does _not_ use the Foswiki rendering, as that is a
lossy conversion, and would make symmetric translation back to TML
an impossibility.
The design goal was to support round-trip conversion from well-formed
TML to XHTML1.0 and back to identical TML. Notes that some deprecated
TML syntax is not supported.
=cut
package Foswiki::Plugins::WysiwygPlugin::TML2HTML;
use Error qw( :try );
use Foswiki;
use Foswiki::Plugins::WysiwygPlugin::Constants;
use strict;
use warnings;
# SMELL: If special characters are added here, they must also be accounted
# for in the sub _protectVerbatimChars
my $TT0 = chr(0);
my $TT1 = chr(1);
my $TT2 = chr(2);
my $TT3 = chr(3); # Temporarily hides noautolink %macros at various points
# HTML elements that are palatable to editors. Other HTML tags will be
# rendered in 'protected' regions to prevent the WYSIWYG editor mussing
# them up. Note that A is specifically excluded from this list because it
# is common for href attributes to contain macros. Users should
# be encouraged to use square bracket formulations for links instead.
my @PALATABLE_TAGS = qw(
ABBR ACRONYM ADDRESS B BDO BIG BLOCKQUOTE BR CAPTION CITE CODE COL
COLGROUP DD DEL DFN DIR DIV DL DT EM FONT H1 H2 H3 H4 H5 H6 HR HTML I IMG INS
ISINDEX KBD LABEL LEGEND LI OL P PRE Q S SAMP SMALL SPAN STRONG SUB SUP TABLE
TBODY TD TFOOT TH THEAD TITLE TR TT U UL STICKY
);
my $PALATABLE_HTML = '(' . join( '|', @PALATABLE_TAGS ) . ')';
# There are several tags that could come before a table tag
my @tagsBeforeTable = (
'<div class="foswikiTableAndMacros">',
'<p>\s*<div class="WYSIWYG_LITERAL">', #SMELL - not valid HTML
'<p>', # from HTML tables not in sticky or literal blocks
);
my $tagsBeforeFirstTablePattern =
'^\\s*(?:' . join( '|', map { $_ . '\\s*' } @tagsBeforeTable ) . ')?<table';
=pod
---++ ClassMethod new()
Construct a new TML to HTML convertor.
=cut
sub new {
my $class = shift;
my $this = {};
return bless( $this, $class );
}
=pod
---++ ObjectMethod convert( $tml, \%options ) -> $tml
Convert a block of TML text into HTML.
Options:
* \&expandVarsInURL is a reference to a static function:<br/>
expandVarsInURL($url, \%options) -> $url<br/>
that expands selected variables in URLs so that, for example,
<img> tags appear as pictures in the wysiwyg editor.
* \&isKnownColour - pointer to a function that will determine if the
parameter maps to a known HTML colour e.g. BLACK -> black and return
the colour name if it does, or undef otherwise.
* \%xmltag is a reference to a hash. The keys are names of XML-like
tags. The values are references to a function to determine if the
content of the tag must be protected:<br/>
fn($markup) -> $bool<br/>
The $markup appears between the <tag></tag> delimiters.
The functions may modify the markup.
* dieonerror makes convert throw an exception if a conversion fails.
The default behaviour is to encode the whole topic as verbatim text.
* \@keeptags - gives an array of HTML tag names that are to have
the TMLhtml class added, to protect them during subsequent
HTML2TML conversion.
* \@keepblocks - gives an array of (lowercase) tag names of HTML block tags
that are to be protected. Default is [ 'script', 'style' ]
* forcenoautolink can be set to a true value to apply NOAUTOLINK
across the entire conversion.
=cut
sub convert {
my ( $this, $content, $options ) = @_;
return '' unless $content;
$this->{opts} = $options;
# Apply defaults to some options
$this->{opts}->{keepblocks} ||= [ 'script', 'style' ];
$this->{opts}->{keeptags} ||= [ 'div', 'span' ];
$this->{opts}->{protectExistingTags} =
{ map { $_ => 1 } @{ $this->{opts}->{keeptags} } };
if ( $this->{opts}->{protectall} ) {
# encode the content verbatim-style, so that the user has
# uncorrupted HTML
$content =~ s/[$TT0$TT1$TT2]/?/go;
$content = _protectVerbatimChars($content);
}
else {
# Convert TML to HTML for wysiwyg editing
$content =~ s/[$TT0$TT1$TT2]/?/go;
# Render TML constructs to tagged HTML
$content = $this->_getRenderedVersion($content);
my $fail = '';
$fail .= "TT0:[$1|TT0|$2]" if $content =~ /(.{0,10})[$TT0](.{0,10})/o;
$fail .= "TT1:[$1|TT1|$2]" if $content =~ /(.{0,10})[$TT1](.{0,10})/o;
$fail .= "TT2:[$1|TT2|$2]" if $content =~ /(.{0,10})[$TT2](.{0,10})/o;
if ($fail) {
# There should never be any of these in the text at this point.
# If there are, then the conversion failed.
die("Invalid characters in HTML after conversion: $fail")
if $options->{dieonerror};
# Encode the original TML as verbatim-style HTML,
# so that the user has uncorrupted TML, at least.
my $originalContent = $_[1];
$originalContent =~ s/[$TT0$TT1$TT2]/?/go;
$originalContent = _protectVerbatimChars($originalContent);
$content = "<div class='WYSIWYG_PROTECTED'>$originalContent</div>";
}
}
# DEBUG
#print STDERR "TML2HTML = '$content'\n";
# This should really use a template, but what the heck...
return $content;
}
sub _liftOut {
my ( $this, $text, $type ) = @_;
my %options;
if ( $type and $type =~ /^(?:PROTECTED|STICKY|VERBATIM)$/ ) {
$options{protect} = 1;
}
$options{class} = 'WYSIWYG_' . $type;
return $this->_liftOutGeneral( $text, \%options );
}
sub _liftOutLink {
my ( $this, $text ) = @_;
my $options = {};
# If link has some embedded macros, just protect it
if ( $text =~ m/%[A-Z]+(\{.*?\})?%/ ) {
return $this->_liftOut( $text, 'PROTECTED' );
}
else {
return $this->_liftOutGeneral( $text,
{ tag => 'NONE', protect => 0, tmltag => 0 } );
}
}
sub _liftOutGeneral {
my ( $this, $text, $options ) = @_;
#$text = $this->_unLift($text);
$options = {} unless ref($options);
my $n = scalar( @{ $this->{refs} } );
push(
@{ $this->{refs} },
{
tag => $options->{tag} || 'span',
text => $text,
tmltag => $options->{tmltag},
params => $options->{params},
class => $options->{class},
protect => $options->{protect},
}
);
return $TT1 . $n . $TT2;
}
sub _unLift {
my ( $this, $text ) = @_;
# Restore everything that was lifted out
while ( $text =~ s#$TT1([0-9]+)$TT2#$this->{refs}->[$1]->{text}#g ) {
}
return $text;
}
sub _dropBack {
my ( $this, $text, $protecting ) = @_;
# Restore everything that was lifted out
while ( $text =~ s#$TT1([0-9]+)$TT2#$this->_dropIn($1, $protecting)#ge ) {
}
return $text;
}
sub _dropIn {
my ( $this, $n, $protecting ) = @_;
my $thing = $this->{refs}->[$n];
my $text = $thing->{text};
#print STDERR "DROPPING IN $text\n";
# Drop back recursively
$text = $this->_dropBack( $text, $protecting || $thing->{protect} );
# Only protect at the outer-most level applicable
$text = _protectVerbatimChars($text)
if $thing->{protect} and not $protecting;
if ($protecting) {
if ( $thing->{tmltag} ) {
return
"<$thing->{tmltag}$thing->{params}>$thing->{text}</$thing->{tmltag}>";
}
else {
return $thing->{text};
}
}
return $thing->{text} if $thing->{tag} eq 'NONE';
$thing->{params} ||= {};
$thing->{params} = _parseParams( $thing->{params} )
if not ref $thing->{params};
_addClass( $thing->{params}->{class}, $thing->{class} ) if $thing->{class};
return
"<$thing->{tag}"
. _attrify( $thing->{params} )
. ">$text</$thing->{tag}>";
}
# Parse and convert macros. If we are not using span markers
# for macros, we have to change the percent signs into entities
# to prevent internal tags being expanded by Foswiki during rendering.
# It's assumed that the editor will have the common sense to convert
# them back to characters when editing.
sub _processTags {
my ( $this, $text ) = @_;
return '' unless defined($text);
# Macros at the start of a line must *stay* at the start of a line.
# The newline preceding the mcro must be preserved.
# This is important for macros like %SEARCH that can emit
# line-oriented TML.
#
# This split captures the preceding newline along with the %,
# if present, as that is a convenient way to include the newline
# in the protected span.
#
# The result is something like this:
# <span class="WYSIWYG_PROTECTED"><br />%TABLESEP%</span>
my @queue = split( /(\n?%)/s, $text );
my @stack;
my $stackTop = '';
while ( scalar(@queue) ) {
my $token = shift(@queue);
if ( $token =~ /^\n?%$/s ) {
if ( $token eq '%' && $stackTop =~ /}$/ ) {
while ( scalar(@stack)
&& $stackTop !~
/^\n?%(?:~~ )?($Foswiki::regex{tagNameRegex}){.*}$/os )
{
$stackTop = pop(@stack) . $stackTop;
}
}
if ( $token eq '%'
&& $stackTop =~
m/^(\n?)%(~~ )?($Foswiki::regex{tagNameRegex})({.*})?$/os )
{
my $nl = $1;
my $glue = $2 || '';
my $tag = $3 . ( $4 || '' );
$tag = "$nl%$glue$tag%";
# Item12341: Clean out protection classes from embedded
# HTML in the tag params. They are not needed because the
# containing span that delimits the macro already protects
# the params.
# SMELL: is TMLhtml the only one we have to deal with?
$tag =~ s/class='TMLhtml'//g;
$tag =~ s/\bTMLhtml\b//g;
# The commented out lines disable PROTECTED for %SIMPLE% vars.
# if ($tag =~ /^\n?%\w+{.*}%/) {
$stackTop =
pop(@stack) . $nl . $this->_liftOut( $tag, 'PROTECTED' );
# } else {
# $stackTop = pop( @stack ).$tag;
# }
}
else {
push( @stack, $stackTop );
$stackTop = $token; # push a new context
}
}
else {
$stackTop .= $token;
}
}
# Run out of input. Gather up everything in the stack.
while ( scalar(@stack) ) {
$stackTop = pop(@stack) . $stackTop;
}
return $stackTop;
}
sub _percentHighBit {
my $url = shift;
return $url if $Foswiki::cfg{Site}{CharSet} eq 'utf-8';
$url =~ s/([\x80-\xFF])/'%'.ord($1)/ge;
return $url;
}
sub _expandURL {
my ( $this, $url ) = @_;
if ( $this->{opts}->{expandVarsInURL} ) {
$url = $this->{opts}->{expandVarsInURL}->( $url, $this->{opts} );
}
return _percentHighBit($url);
}
# Lifted straight out of DevelopBranch Render.pm
# Then modified to include TablePlugin's approach to table rendering
sub _getRenderedVersion {
my ( $this, $text, $refs ) = @_;
return '' unless $text; # nothing to do
@{ $this->{LIST} } = ();
$this->{refs} = [];
# Initial cleanup
$text =~ s/\r//g;
$text =~ s/^\n*//s;
$text =~ s/\n*$//s;
$this->{removed} = {}; # Map of placeholders to tag parameters and text
# Do sticky first; it can't be ignored
$text = $this->_liftOutBlocks(
$text, 'sticky',
{
tag => 'div',
protect => 1,
class => 'WYSIWYG_STICKY'
}
);
$text = $this->_liftOutBlocks(
$text,
'verbatim',
{
tag => 'pre',
protect => 1,
class => 'TMLverbatim'
}
);
$text = $this->_liftOutBlocks(
$text,
'literal',
{
tag => 'div',
class => 'WYSIWYG_LITERAL'
}
);
$text = $this->_takeOutSets($text);
$text = $this->_takeOutCustomTags($text);
$text =~ s/\t/ /g;
$text =~ s/(\\\n)/$this->_hideWhitespace($1)/ge;
# Remove PRE to prevent TML interpretation of text inside it
$text = $this->_liftOutBlocks( $text, 'pre', {} );
# protect some sticky block tags.
foreach my $stickyTag ( @{ $this->{opts}->{keepblocks} } ) {
$text =~ s/(<(?i:$stickyTag)[^>]*>.*?<\/(?i:$stickyTag)>)/
$this->_liftOut($1, 'PROTECTED')/geis;
}
# protect   by making it sticky
$text =~ s/( )/$this->_liftOut($1, 'STICKY')/ges;
# Protect comments
$text =~ s/(<!--.*?-->)/$this->_liftOut($1, 'PROTECTED')/ges;
# Protect anchors
$text =~
s/^($Foswiki::regex{anchorRegex})/$this->_liftOut("\n$1", 'PROTECTED')/gems;
# Handle inline IMG tags specially
$text =~ s/(<img [^>]*>)/$this->_takeOutIMGTag($1)/gei;
$text =~ s/<\/img>//gi;
# Protect HTML (including HTML that appears in tag params) with a
# special class
$text =~
s/<([A-Za-z]+[^>]*?)((?:\s+\/)?)>/'<' . $this->_protectTag($1, 'TMLhtml') . $2 . '>'/ge;
# Handle colour tags specially (hack, hack, hackity-HACK!)
my $colourMatch = join( '|', grep( /^[A-Z]/, @WC::TML_COLOURS ) );
$text =~ s#%($colourMatch)%(.*?)%ENDCOLOR%#
$this->_getNamedColour($1, $2)#ge;
# let WYSIWYG-editable A tags untouched for the editor
$text =~ s/(\<a
(?:\s+
(?: href|target|title|class )= # Supported attribute
(?: \'[^\']*\' | \"[^\"]*\" | [^\'\"\s]+ )+ # One or more SQ, DQ or space delimited strings
)+ # One or more attributes - href is required
\s*\>
.*? # the link text
\<\/a\s*\> # closing tag
)/
$this->_liftOutLink($1, { tag => 'NONE', protect => 0, tmltag => 0 } )/geixo;
$text =~
s/(?<!\!)\[\[([^]]*)\]\[([^]]*)\]\]/$this->_protectMacrosInSquab($1,$2)/ge;
$text =~ s/(?<!\!)\[\[([^\]]*)\]\]/$this->_protectMacrosInSquab($1)/ge;
$text =~ s/(<[^>]+>)/$this->_protectMacrosInHTML($1)/ge;
# Convert Foswiki tags to spans outside protected text
$text = $this->_processTags($text);
# Unprotect the macros.
$text =~ s/$TT3/%/g;
# Handle [[][]] links by letting the WYSIWYG handle them as standard links
$text =~
s/(?<!\!)\[\[([^]]*)\]\[([^]]*)\]\]/$this->_liftOutSquab($1,$2,'TMLlink')/ge;
# Handle [[]] links
$text =~ s/(?<!\!)\[\[([^\]]*)\]\]/$this->_liftOutSquab($1,$1,'TMLlink')/ge;
# protect some HTML tags, excluding noautolink and nop, handled later.
$text =~ s/(<\/?(?!(?i:$PALATABLE_HTML|NOAUTOLINK|NOP)\b)[A-Z]+(\s[^>]*)?>)/
$this->_liftOut($1, 'PROTECTED')/gei;
# hide NOAUTOLINK and NOP
$text =~ s/<(\/?noautolink)>/$TT3$1$TT3/gi;
$text =~ s/<(nop)>/$TT3$1$TT3/gi;
# Blockquoted email (indented with '> ')
# Could be used to provide different colours for different numbers of '>'
$text =~ s/^>(.*?)$/><cite class='TMLcite'>$1<\/cite><br\/>/gm;
# locate isolated < and > and translate to entities
# Protect isolated <!-- and -->
$text =~ s/<!--/{$TT0!--/g;
$text =~ s/-->/--}$TT0/g;
# SMELL: this next fragment is a frightful hack, to handle the
# case where simple HTML tags (i.e. without values) are embedded
# in the values provided to other tags. The only way to do this
# correctly (i.e. handle HTML tags with values as well) is to
# parse the HTML (bleagh!)
$text =~ s/<(\/[A-Za-z]+)>/{$TT0$1}$TT0/g;
$text =~ s/<([A-Za-z]+(\s+\/)?)>/{$TT0$1}$TT0/g;
$text =~ s/<(\S.*?)>/{$TT0$1}$TT0/g;
# entitify lone < and >, praying that we haven't screwed up :-(
$text =~ s/</<\;/g;
$text =~ s/>/>\;/g;
$text =~ s/{$TT0/</go;
$text =~ s/}$TT0/>/go;
# standard URI
$text =~
s/((^|(?<=[-*\s(]))$Foswiki::regex{linkProtocolPattern}:[^\s<>"]+[^\s*.,!?;:)<])/$this->_liftOut($1, 'LINK')/geo;
# other entities
# SMELL - international characters are not allowed in entity names
$text =~ s/&([$Foswiki::regex{mixedAlphaNum}]+;)/$TT0$1/g; # "&abc;"
$text =~ s/&(#[0-9]+;)/$TT0$1/g; # "{"
#$text =~ s/&/&/g; # escape standalone "&"
$text =~ s/$TT0(#[0-9]+;)/&$1/go;
$text =~ s/$TT0([$Foswiki::regex{mixedAlphaNum}]+;)/&$1/go;
# Horizontal rule
$text =~ s/^(---+)$/_encodeHr($1)/gme;
# Wrap tables with macros before or after them in a <div>,
# together with the macros,
# so that TMCE may be used without the force_root_block option
my @lines = split( /\n/, $text );
my $divableStartLine = undef;
my $hasTable = 0;
my $hasMacro = 0;
my @divIndexes = ();
for my $lineNumber ( 0 .. $#lines ) {
# Table: | cell | cell |
# allow trailing white space after the last |
if ( $lines[$lineNumber] =~ m/^\s*\|.*\|\s*$/ ) {
$divableStartLine = $lineNumber
if not defined $divableStartLine;
$hasTable = 1;
}
# Macro, after it was lifted out by _processTags
elsif ( $lines[$lineNumber] =~ m/$TT1(\d+)$TT2/
and $this->{refs}->[$1]->{text} =~ /^\n?%/ )
{
$divableStartLine = $lineNumber
if not defined $divableStartLine;
$hasMacro = 1;
}
# Neither table line nor macro
else {
if ( defined $divableStartLine ) {
if ( $hasMacro and $hasTable ) {
push @divIndexes,
{ start => $divableStartLine, end => $lineNumber };
}
undef $divableStartLine;
$hasMacro = 0;
$hasTable = 0;
}
}
}
if ( defined $divableStartLine ) {
if ( $hasMacro and $hasTable ) {
push @divIndexes, { start => $divableStartLine, end => $#lines };
}
}
my $tableAndMacrosDivStart = '<div class="foswikiTableAndMacros">';
my $tableAndMacrosDivEnd = '</div><!--foswikiTableAndMacros-->';
while (@divIndexes) {
# Work backwards from the end,
# so that the indexes are correct as they are processed
my $set = pop @divIndexes;
splice @lines, $set->{end} + 1, 0, $tableAndMacrosDivEnd;
splice @lines, $set->{start}, 0, $tableAndMacrosDivStart;
}
$text = join( "\n", @lines );
# Now we really _do_ need a line loop, to process TML
# line-oriented stuff.
my $inList = 0; # True when within a list type
my $inTable = 0; # True when within a table type
my $inHTMLTable = 0; # True when within a native HTML table
my %table = ();
my $inParagraph = 0; # True when within a P
# SMELL This next one should probably be split
my $inDiv = 0; # True when within a div or blockquote
my @result = ();
foreach my $line ( split( /\n/, $text ) ) {
my $tableEnded = 0;
if ($inHTMLTable) {
if ( $line =~ m/<\/table>/i ) {
$inHTMLTable = 0;
$this->_addListItem( \@result, '', '', '' ) if $inList;
$inList = 0;
push( @result, $line );
next;
}
elsif ( !$line || $line =~ m/^\s*$/ ) {
push( @result, '</p>' ) if ($inParagraph);
push( @result, '<p></p>' );
$inParagraph = 0;
next;
}
}
if ( $line =~ m/<table/i ) {
$inHTMLTable = 1;
if ($inParagraph) {
push( @result, '</p>' );
$inParagraph = 0;
}
}
# Table: | cell | cell |
# allow trailing white space after the last |
if ( $line =~ m/^(\s*\|.*\|\s*)$/ ) {
push( @result, '</p>' ) if $inParagraph;
$inParagraph = 0;
$this->_addListItem( \@result, '', '', '', '' ) if $inList;
$inList = 0;
push( @result, _processTableRow( $1, $inTable, \%table ) );
$inTable = 1;
next;
}
if ($inTable) {
push( @result, _emitTable( \%table ) );
$inTable = 0;
$tableEnded = 1;
}
if ( $line =~ /$Foswiki::regex{headerPatternDa}/o ) {
# Running head
$this->_addListItem( \@result, '', '', '', '' ) if $inList;
$inList = 0;
push( @result, '</p>' ) if $inParagraph;
$inParagraph = 0;
my ( $indicator, $heading ) = ( $1, $2 );
my $class = 'TML';
if ( $heading =~ s/$Foswiki::regex{headerPatternNoTOC}//o ) {
$class .= ' notoc';
}
if ( $indicator =~ /#/ ) {
$class .= ' numbered';
}
my $l = length($indicator);
$line = "<h$l class='$class'> $heading </h$l>";
}
elsif ( $line =~ /^\s*$/ ) {
# Blank line
my $class = '';
if ( not $inParagraph ) {
$class = 'WYSIWYG_NBNL';
}
$class = " class='$class'" if $class;
push( @result, '</p>' ) if $inParagraph;
$inParagraph = 0;
if ($inHTMLTable) {
$line = '<p' . $class . '></p>';
$this->_addListItem( \@result, '', '', '', '' ) if $inList;
$inList = 0;
}
else {
$line = '<p' . $class . '>';
$this->_addListItem( \@result, '', '', '', '' ) if $inList;
$inList = 0;
$inParagraph = 1;
}
}
elsif ( $line =~
s/^((\t| )+)\$\s(([^:]+|:[^\s]+)+?):\s/<dt> $3 <\/dt><dd> /o )
{
# Definition list
push( @result, '</p>' ) if $inParagraph;
$inParagraph = 0;
$this->_addListItem( \@result, 'dl', 'dd', '', $1 );
$inList = 1;
}
elsif ( $line =~ s/^((\t| )+)(\S+?):\s/<dt> $3<\/dt><dd> /o ) {
# Definition list
push( @result, '</p>' ) if $inParagraph;
$inParagraph = 0;
$this->_addListItem( \@result, 'dl', 'dd', '', $1 );
$inList = 1;
}
elsif ( $line =~ s/^((\t| )+)\*(\s|$)/<li> /o ) {
# Unnumbered list
push( @result, '</p>' ) if $inParagraph;
$inParagraph = 0;
$this->_addListItem( \@result, 'ul', 'li', '', $1 );
$inList = 1;
# TinyMCE won't let the cursor go into an empty element
# so make sure that the element isn't empty.
$line =~ s/^(<li>)\s*$/$1 /;
}
elsif ($this->{opts}->{supportsparaindent}
&& $line =~ s/^((\t| )+): /<div class='foswikiIndent'> /o )
{
# Indent pseudo-list
$this->_addListItem( \@result, '', 'div', 'class="foswikiIndent"',
$1 );
$inList = 1;
}
elsif ( $line =~ m/^((\t| )+)([1AaIi]\.|\d+\.?) ?/ ) {
# Numbered list
push( @result, '</p>' ) if $inParagraph;
$inParagraph = 0;
my $ot = $3;
$ot =~ s/^(.).*/$1/;
if ( $ot !~ /^\d$/ ) {
$ot = ' type="' . $ot . '"';
}
else {
$ot = '';
}
$line =~ s/^((\t| )+)([1AaIi]\.|\d+\.?) ?/<li$ot> /;
$this->_addListItem( \@result, 'ol', 'li', '', $1 );
$inList = 1;
# TinyMCE won't let the cursor go into an empty element
# so make sure that the element isn't empty.
$line =~ s/^(<li\Q$ot\E>)\s*$/$1 /;
}
elsif ($inList
&& $line =~ s/^([ \t]+)/$this->_hideWhitespace("\n$1")/e )
{
# Extend text of previous list item by dropping through
$result[-1] .= $line;
$line = '';
}
elsif ( $line =~ /^<hr class="TMLhr"/ ) {
push( @result, '</p>' ) if $inParagraph;
$inParagraph = 0;
}
elsif ( $line eq $tableAndMacrosDivStart ) {
push( @result, '</p>' ) if $inParagraph;
$inParagraph = 0;
$this->_addListItem( \@result, '', '', '' ) if $inList;
$inList = 0;
$inDiv++;
}
elsif ( $line eq $tableAndMacrosDivEnd ) {
$this->_addListItem( \@result, '', '', '' ) if $inList;
$inList = 0;
$inDiv--;
# The comment was only needed for this test,
# and it must be removed to prevent it ending up in TML
$line = '</div>';
}
elsif ( $line =~ m/<div|<blockquote/i ) {
# If open/close on same line, then don't increment $inDiv
# SMELL: This is really lame.
unless ( $line =~ m/<(div|blockquote).*<\/\1/ ) {
$inDiv++;
}
if ($inParagraph) {
push( @result, '</p>' );
$inParagraph = 0;
}
elsif (@result) {
# Don't double-up the whitespace.
unless ($result[-1] =~ m/$TT1(\d+)$TT2/
and $this->{refs}->[$1]->{params} =~ /encoded:'n'/ )
{
$line = $this->_hideWhitespace("\n") . $line;
}
}
}
else {
#print STDERR "Fallthru processing $line\n";
# Other line
$this->_addListItem( \@result, '', '', '' ) if $inList;
$inList = 0;
if ( ( $inParagraph or $inHTMLTable or $inDiv )
and @result
and $result[-1] !~ /<p(?: class='[^']+')?>$/ )
{
# This is the second (or later) line of a paragraph
my $whitespace = "\n";
if ( $line =~ m/^$TT1(\d+)$TT2/
and $this->{refs}->[$1]->{text} =~ /^\n?%/ )
{
#print STDERR "------- NEWLINE IS ALREADY PROTECTED\n";
# The newline is already protected
$whitespace = "";
}
# Closing div or blockquote already had whitespace handled
$whitespace = '' if ( $line =~ m/<\/div|<\/blockquote/i );
if ( $line =~ s/^(\s+)// ) {
$whitespace .= $1;
}
#print STDERR "Hiding whitespace ($whitespace)\n";
$line = $this->_hideWhitespace($whitespace) . $line
if length($whitespace);
}
unless ( $inParagraph or $inDiv ) {
unless ($inHTMLTable) {
#print STDERR "pushed <p>\n";
push( @result, '<p>' );
$inParagraph = 1;
}
}
if ( $line =~ m/<\/div|<\/blockquote/i ) {
if ($inParagraph) {
#print STDERR "Closing para before close blockquote/div\n";
push( @result, '</p>' );
$inParagraph = 0;
}
# Don't let the close div auto-wrap onto the prior line
elsif ( defined $result[-1]
&& $line =~ /^<\/div|<\/blockquote/i )
{
$result[-1] .= $this->_hideWhitespace("\n");
}
$inDiv--;
}
$line =~ s/(\s\s+)/$this->_hideWhitespace($1)/ge;
if ( defined $result[-1] ) {
$result[-1] .= " "
. $line
; # Item13207: add a whitespace here so that any following TML is recognized
$line = '';
}
}
push( @result, $line ) if length($line) > 0;
}
if ($inTable) {
push( @result, _emitTable( \%table ) );
}
elsif ($inList) {
$this->_addListItem( \@result, '', '', '' );
}
elsif ($inParagraph) {
#print STDERR "autoClosing a p\n";
push( @result, '</p>' );
}
elsif ($inDiv) {
# SMELL: This could also be an unclosed blockquote :(
#print STDERR "autoClosing a div\n";
push( @result, '</div>' );
}
$text = join( "\n", @result );
#print STDERR "BEFORE DROPINS \n[",$text,"]\n";
# Trim any extra Ps from the top and bottom.
$text =~ s#^(\s*<p>\s*</p>)+##s;
$text =~ s#(<p>\s*</p>\s*)+$##s;
_handleMarkup($text);
# restore NOAUTOLINK
$text =~ s/$TT3(\/?noautolink)$TT3/<$1>/gi;
unless ( $this->{opts}->{forcenoautolink} ) {
my $removed = {};
$text = Foswiki::takeOutBlocks( $text, 'noautolink', $removed );
# Need to also include protected content marker as part of
# start wikiword delim
my $startww = qr/$WC::STARTWW|(?<=$TT2)/;
$text =~
s/$startww(($Foswiki::regex{webNameRegex}\.)?$Foswiki::regex{wikiWordRegex}($Foswiki::regex{anchorRegex})?)/$this->_liftOutSquab($1,$1)/geom;
Foswiki::putBackBlocks( \$text, $removed, 'noautolink' );
}
# protect NOAUTOLINK.
$text =~ s/(<\/?(?i:noautolink\b)(\s[^>]*)?>)/
$this->_liftOut($1, 'PROTECTED')/gei;
# Restore and protect NOP
$text =~ s/$TT3(nop)$TT3/<$1>/gi;
$text =~ s/(<nop>)/$this->_liftOut($1, 'PROTECTED')/ge;
# Substitute back in protected elements
$text = $this->_dropBack($text);
# Restore any missed protected % tags
# (They are only restored in outer level of nested tags)
$text =~ s/$TT3/%/g;
# Item1417: Insert a paragraph at the start of the document if the first tag
# is a table (possibly preceded one of several specific tags) so that it is
# possible to place the cursor *above* the table.
# The paragraph is removed automatically if it is empty, when converting
# back to TML.
if ( $text =~ /$tagsBeforeFirstTablePattern/o ) {
$text = '<p class="foswikiDeleteMe"> </p>' . $text;
}
elsif ( $text =~ /^\s*(?:<p>)?\s*<(?:pre|blockquote|div)/o ) {
$text = '<p class="foswikiDeleteMe"> </p>' . $text;
}
# SMELL: "Enter" in TMCE will split a blockquote into multiple blockquote elements.
# This wraps the contents in a paragraph, and avoids the split. It will be removed on save.
$text =~
s/(<blockquote.*?>)(.*?)(<\/blockquote)/$1<p class="foswikiDeleteMe">$2<\/p>$3/sgi;
#print STDERR "DEBUG\n$text\n";
return $text;
}
sub _liftOutSquab {
my $this = shift;
my $url = shift;
my $text = shift;
my $class = shift || '';
my $dataWikiword = '';
# Treat as old style link if embedded spaces in the url
return $this->_liftOut( '[[' . $url . ']]', 'LINK' )
if ( $class eq 'TMLlink' && $url =~ m/\s/ && $url eq $text );
# Treat as old link if embedded quotes, which will break href=
if ( $url =~ m/"/ ) {
#print STDERR "protecting due to embedded quotes - $url\n";
my $linktext = ($text) ? "[$text]" : '';
return $this->_liftOut( '[[' . $url . ']' . $linktext . ']', 'LINK' );
}
# Handle colour tags specially (hack, hack, hackity-HACK!
my $colourMatch = join( '|', grep( /^[A-Z]/, @WC::TML_COLOURS ) );
$text =~ s#%($colourMatch)%(.*?)%ENDCOLOR%#
$this->_getNamedColour($1, $2)#oge;
_handleMarkup($text);
my $startww = qr/$WC::STARTWW|(?<=$TT2)/;
if ( $url =~
m/$startww(($Foswiki::regex{webNameRegex}\.)?$Foswiki::regex{wikiWordRegex}($Foswiki::regex{anchorRegex})?)/
&& $url eq $text )
{
$dataWikiword = " data-wikiword='$url'";
}
if ($class) {
$class = " class='$class'";
}
$url = _percentHighBit($url);
return $this->_liftOutGeneral(
"<a$class$dataWikiword href=\"$url\">$text<\/a>",
{ tag => 'NONE', protect => 0, tmltag => 0 }
);
}
sub _protectMacrosInHTML {
my $this = shift;
my $tag = shift;
$tag =~ s/%/$TT3/g;
return $tag;
}
sub _protectMacrosInSquab {
my $this = shift;
my $url = shift;
my $text = shift;