-
Notifications
You must be signed in to change notification settings - Fork 2
/
latexdiff-so
executable file
·3240 lines (2727 loc) · 110 KB
/
latexdiff-so
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
#!/usr/bin/perl -w
# latexdiff - differences two latex files on the word level
# and produces a latex file with the differences marked up.
#
# Copyright (C) 2004-2007 F J Tilmann ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License Version 2 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Detailed usage information at the end of the file
#
# Version 0.5 A number of minor improvements based on feedback
# Deleted blocks are now shown before added blocks
# Package specific processing
#
# Version 0.43 unreleased typo in list of styles at the end
# Add protect to all \cbstart, \cbend commands
# More robust substitution of deleted math commands
#
# Version 0.42 November 06 Bug fixes only
#
# Version 0.4 March 06 option for fast differencing using UNIX diff command, several minor bug fixes (\par bug, improved highlighting of textcmds)
#
# Version 0.3 August 05 improved parsing of displayed math, --allow-spaces
# option, several minor bug fixes
#
# Version 0.25 October 04 Fix bug with deleted equations, add math mode commands to safecmd, add | to allowed interpunctuation signs
# Version 0.2 September 04 extension to utf-8 and variable encodings
# Version 0.1 August 04 First public release
# Inserted block for stand-alone version replaces
# use Algorithm::Diff qw(traverse_sequences);
# in standard version
# The following BEGIN block contains a verbatim copy of
# Ned Konz' Algorithm::Diff package version 1.15 except
# that all POD documentation has been stripped out.
# I encourage you to download and install the Algorithm::Diff
# package and use the standard latexdiff version instead
# (current distribution available from http://search.cpan.org/~nedkonz/Algorithm-Diff-1.15
# the most recent version can be found via http://search.cpan.org/search?module=Algorithm::Diff )
# Please note that the LICENCSE for Algorithm::Diff :
# "Copyright (c) 2000-2002 Ned Konz. All rights reserved.
# This program is free software;
# you can redistribute it and/or modify it under the same terms
# as Perl itself."
# The stand-alone version of latexdiff is provided as a convenience
# for latex users with no knowledge of PERL who do not wish to install
# additional packages to be able to use latexdiff. If you believe
# the inlining of Algorithm::Diff violates its license please contact
# me and I will modify the latexdiff distribution accordingly.
# Frederik Tilmann ([email protected])
BEGIN {
package Algorithm::Diff;
use strict;
use vars qw($VERSION @EXPORT_OK @ISA @EXPORT);
use integer; # see below in _replaceNextLargerWith() for mod to make
# if you don't use this
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw();
@EXPORT_OK = qw(LCS diff traverse_sequences traverse_balanced sdiff);
$VERSION = sprintf('%d.%02d so', (q$Revision: 1.15 $ =~ /\d+/g));
# McIlroy-Hunt diff algorithm
# Adapted from the Smalltalk code of Mario I. Wolczko, <[email protected]>
# by Ned Konz, [email protected]
# Create a hash that maps each element of $aCollection to the set of positions
# it occupies in $aCollection, restricted to the elements within the range of
# indexes specified by $start and $end.
# The fourth parameter is a subroutine reference that will be called to
# generate a string to use as a key.
# Additional parameters, if any, will be passed to this subroutine.
#
# my $hashRef = _withPositionsOfInInterval( \@array, $start, $end, $keyGen );
sub _withPositionsOfInInterval
{
my $aCollection = shift; # array ref
my $start = shift;
my $end = shift;
my $keyGen = shift;
my %d;
my $index;
for ( $index = $start ; $index <= $end ; $index++ )
{
my $element = $aCollection->[$index];
my $key = &$keyGen( $element, @_ );
if ( exists( $d{$key} ) )
{
unshift ( @{ $d{$key} }, $index );
}
else
{
$d{$key} = [$index];
}
}
return wantarray ? %d : \%d;
}
# Find the place at which aValue would normally be inserted into the array. If
# that place is already occupied by aValue, do nothing, and return undef. If
# the place does not exist (i.e., it is off the end of the array), add it to
# the end, otherwise replace the element at that point with aValue.
# It is assumed that the array's values are numeric.
# This is where the bulk (75%) of the time is spent in this module, so try to
# make it fast!
sub _replaceNextLargerWith
{
my ( $array, $aValue, $high ) = @_;
$high ||= $#$array;
# off the end?
if ( $high == -1 || $aValue > $array->[-1] )
{
push ( @$array, $aValue );
return $high + 1;
}
# binary search for insertion point...
my $low = 0;
my $index;
my $found;
while ( $low <= $high )
{
$index = ( $high + $low ) / 2;
# $index = int(( $high + $low ) / 2); # without 'use integer'
$found = $array->[$index];
if ( $aValue == $found )
{
return undef;
}
elsif ( $aValue > $found )
{
$low = $index + 1;
}
else
{
$high = $index - 1;
}
}
# now insertion point is in $low.
$array->[$low] = $aValue; # overwrite next larger
return $low;
}
# This method computes the longest common subsequence in $a and $b.
# Result is array or ref, whose contents is such that
# $a->[ $i ] == $b->[ $result[ $i ] ]
# foreach $i in ( 0 .. $#result ) if $result[ $i ] is defined.
# An additional argument may be passed; this is a hash or key generating
# function that should return a string that uniquely identifies the given
# element. It should be the case that if the key is the same, the elements
# will compare the same. If this parameter is undef or missing, the key
# will be the element as a string.
# By default, comparisons will use "eq" and elements will be turned into keys
# using the default stringizing operator '""'.
# Additional parameters, if any, will be passed to the key generation routine.
sub _longestCommonSubsequence
{
my $a = shift; # array ref
my $b = shift; # array ref
my $keyGen = shift; # code ref
my $compare; # code ref
# set up code refs
# Note that these are optimized.
if ( !defined($keyGen) ) # optimize for strings
{
$keyGen = sub { $_[0] };
$compare = sub { my ( $a, $b ) = @_; $a eq $b };
}
else
{
$compare = sub {
my $a = shift;
my $b = shift;
&$keyGen( $a, @_ ) eq &$keyGen( $b, @_ );
};
}
my ( $aStart, $aFinish, $bStart, $bFinish, $matchVector ) =
( 0, $#$a, 0, $#$b, [] );
# First we prune off any common elements at the beginning
while ( $aStart <= $aFinish
and $bStart <= $bFinish
and &$compare( $a->[$aStart], $b->[$bStart], @_ ) )
{
$matchVector->[ $aStart++ ] = $bStart++;
}
# now the end
while ( $aStart <= $aFinish
and $bStart <= $bFinish
and &$compare( $a->[$aFinish], $b->[$bFinish], @_ ) )
{
$matchVector->[ $aFinish-- ] = $bFinish--;
}
# Now compute the equivalence classes of positions of elements
my $bMatches =
_withPositionsOfInInterval( $b, $bStart, $bFinish, $keyGen, @_ );
my $thresh = [];
my $links = [];
my ( $i, $ai, $j, $k );
for ( $i = $aStart ; $i <= $aFinish ; $i++ )
{
$ai = &$keyGen( $a->[$i], @_ );
if ( exists( $bMatches->{$ai} ) )
{
$k = 0;
for $j ( @{ $bMatches->{$ai} } )
{
# optimization: most of the time this will be true
if ( $k and $thresh->[$k] > $j and $thresh->[ $k - 1 ] < $j )
{
$thresh->[$k] = $j;
}
else
{
$k = _replaceNextLargerWith( $thresh, $j, $k );
}
# oddly, it's faster to always test this (CPU cache?).
if ( defined($k) )
{
$links->[$k] =
[ ( $k ? $links->[ $k - 1 ] : undef ), $i, $j ];
}
}
}
}
if (@$thresh)
{
for ( my $link = $links->[$#$thresh] ; $link ; $link = $link->[0] )
{
$matchVector->[ $link->[1] ] = $link->[2];
}
}
return wantarray ? @$matchVector : $matchVector;
}
sub traverse_sequences
{
my $a = shift; # array ref
my $b = shift; # array ref
my $callbacks = shift || {};
my $keyGen = shift;
my $matchCallback = $callbacks->{'MATCH'} || sub { };
my $discardACallback = $callbacks->{'DISCARD_A'} || sub { };
my $finishedACallback = $callbacks->{'A_FINISHED'};
my $discardBCallback = $callbacks->{'DISCARD_B'} || sub { };
my $finishedBCallback = $callbacks->{'B_FINISHED'};
my $matchVector = _longestCommonSubsequence( $a, $b, $keyGen, @_ );
# Process all the lines in @$matchVector
my $lastA = $#$a;
my $lastB = $#$b;
my $bi = 0;
my $ai;
for ( $ai = 0 ; $ai <= $#$matchVector ; $ai++ )
{
my $bLine = $matchVector->[$ai];
if ( defined($bLine) ) # matched
{
&$discardBCallback( $ai, $bi++, @_ ) while $bi < $bLine;
&$matchCallback( $ai, $bi++, @_ );
}
else
{
&$discardACallback( $ai, $bi, @_ );
}
}
# The last entry (if any) processed was a match.
# $ai and $bi point just past the last matching lines in their sequences.
while ( $ai <= $lastA or $bi <= $lastB )
{
# last A?
if ( $ai == $lastA + 1 and $bi <= $lastB )
{
if ( defined($finishedACallback) )
{
&$finishedACallback( $lastA, @_ );
$finishedACallback = undef;
}
else
{
&$discardBCallback( $ai, $bi++, @_ ) while $bi <= $lastB;
}
}
# last B?
if ( $bi == $lastB + 1 and $ai <= $lastA )
{
if ( defined($finishedBCallback) )
{
&$finishedBCallback( $lastB, @_ );
$finishedBCallback = undef;
}
else
{
&$discardACallback( $ai++, $bi, @_ ) while $ai <= $lastA;
}
}
&$discardACallback( $ai++, $bi, @_ ) if $ai <= $lastA;
&$discardBCallback( $ai, $bi++, @_ ) if $bi <= $lastB;
}
return 1;
}
sub traverse_balanced
{
my $a = shift; # array ref
my $b = shift; # array ref
my $callbacks = shift || {};
my $keyGen = shift;
my $matchCallback = $callbacks->{'MATCH'} || sub { };
my $discardACallback = $callbacks->{'DISCARD_A'} || sub { };
my $discardBCallback = $callbacks->{'DISCARD_B'} || sub { };
my $changeCallback = $callbacks->{'CHANGE'};
my $matchVector = _longestCommonSubsequence( $a, $b, $keyGen, @_ );
# Process all the lines in match vector
my $lastA = $#$a;
my $lastB = $#$b;
my $bi = 0;
my $ai = 0;
my $ma = -1;
my $mb;
while (1)
{
# Find next match indices $ma and $mb
do { $ma++ } while ( $ma <= $#$matchVector && !defined $matchVector->[$ma] );
last if $ma > $#$matchVector; # end of matchVector?
$mb = $matchVector->[$ma];
# Proceed with discard a/b or change events until
# next match
while ( $ai < $ma || $bi < $mb )
{
if ( $ai < $ma && $bi < $mb )
{
# Change
if ( defined $changeCallback )
{
&$changeCallback( $ai++, $bi++, @_ );
}
else
{
&$discardACallback( $ai++, $bi, @_ );
&$discardBCallback( $ai, $bi++, @_ );
}
}
elsif ( $ai < $ma )
{
&$discardACallback( $ai++, $bi, @_ );
}
else
{
# $bi < $mb
&$discardBCallback( $ai, $bi++, @_ );
}
}
# Match
&$matchCallback( $ai++, $bi++, @_ );
}
while ( $ai <= $lastA || $bi <= $lastB )
{
if ( $ai <= $lastA && $bi <= $lastB )
{
# Change
if ( defined $changeCallback )
{
&$changeCallback( $ai++, $bi++, @_ );
}
else
{
&$discardACallback( $ai++, $bi, @_ );
&$discardBCallback( $ai, $bi++, @_ );
}
}
elsif ( $ai <= $lastA )
{
&$discardACallback( $ai++, $bi, @_ );
}
else
{
# $bi <= $lastB
&$discardBCallback( $ai, $bi++, @_ );
}
}
return 1;
}
sub LCS
{
my $a = shift; # array ref
my $matchVector = _longestCommonSubsequence( $a, @_ );
my @retval;
my $i;
for ( $i = 0 ; $i <= $#$matchVector ; $i++ )
{
if ( defined( $matchVector->[$i] ) )
{
push ( @retval, $a->[$i] );
}
}
return wantarray ? @retval : \@retval;
}
sub diff
{
my $a = shift; # array ref
my $b = shift; # array ref
my $retval = [];
my $hunk = [];
my $discard = sub { push ( @$hunk, [ '-', $_[0], $a->[ $_[0] ] ] ) };
my $add = sub { push ( @$hunk, [ '+', $_[1], $b->[ $_[1] ] ] ) };
my $match = sub { push ( @$retval, $hunk ) if scalar(@$hunk); $hunk = [] };
traverse_sequences( $a, $b,
{ MATCH => $match, DISCARD_A => $discard, DISCARD_B => $add }, @_ );
&$match();
return wantarray ? @$retval : $retval;
}
sub sdiff
{
my $a = shift; # array ref
my $b = shift; # array ref
my $retval = [];
my $discard = sub { push ( @$retval, [ '-', $a->[ $_[0] ], "" ] ) };
my $add = sub { push ( @$retval, [ '+', "", $b->[ $_[1] ] ] ) };
my $change = sub {
push ( @$retval, [ 'c', $a->[ $_[0] ], $b->[ $_[1] ] ] );
};
my $match = sub {
push ( @$retval, [ 'u', $a->[ $_[0] ], $b->[ $_[1] ] ] );
};
traverse_balanced(
$a,
$b,
{
MATCH => $match,
DISCARD_A => $discard,
DISCARD_B => $add,
CHANGE => $change,
},
@_
);
return wantarray ? @$retval : $retval;
}
1;
}
import Algorithm::Diff qw(traverse_sequences);
# End of inserted block for stand-alone version
use Getopt::Long ;
use strict ;
use utf8 ;
my ($algodiffversion)=split(/ /,$Algorithm::Diff::VERSION);
my ($versionstring)=<<EOF ;
This is LATEXDIFF 0.5 (Algorithm::Diff $Algorithm::Diff::VERSION)
(c) 2004-2007 F J Tilmann
EOF
# Configuration variables: these have to be visible from the subroutines
my $MINWORDSBLOCK=3; # minimum number of tokens to form an independent block
# shorter identical blocks will be merged to the previous word
my $FLOATENV='(?:figure|table|plate)[\w\d*@]*' ; # Environments in which FL variants of defined commands are used
my $PICTUREENV='(?:picture|DIFnomarkup)[\w\d*@]*' ; # Environments in which all change markup is removed
my $MATHENV='(?:equation|displaymath|DOLLARDOLLAR)' ; # Environments turning on display math mode (code also knows about \[ and \]
my $MATHREPL='displaymath'; # Environment introducing deleted maths blocks
my $MATHARRENV='(?:eqnarray|align|gather|multiline|flalign)[*]?' ; # Environments turning on eqnarray math mode
my $MATHARRREPL='eqnarray*'; # Environment introducing deleted maths blocks
my $ARRENV='(?:array|[pbvBV]matrix)'; # Enviroments making arrays in math mode. The underlining style does not cope well with those - as a result in-text math environments are surrounded by \mbox{ } if any of these commands is used in an inline math block
my $COUNTERCMD='(?:footnote|part|section|subsection|subsubsection|paragraph|subparagraph)'; # textcmds which are associated with a counter
# If any of these commands occur in a deleted block
# they will be succeeded by an \addtocounter{...}{-1}
# for the associated counter such that the overall numbers
# should be the same as in the new file
# Markup strings
# If at all possible, do not change these as parts of the program
# depend on the actual name (particularly post-processing)
# At the very least adapt subroutine postprocess to new tokens.
my $ADDMARKOPEN='\DIFaddbegin '; # Token to mark begin of appended text
my $ADDMARKCLOSE='\DIFaddend '; # Token to mark end of appended text
my $ADDOPEN='\DIFadd{'; # To mark begin of added text passage
my $ADDCLOSE='}'; # To mark end of added text passage
my $ADDCOMMENT='DIF > '; # To mark added comment line
my $DELMARKOPEN='\DIFdelbegin '; # Token to mark begin of deleted text
my $DELMARKCLOSE='\DIFdelend '; # Token to mark end of deleted text
my $DELOPEN='\DIFdel{'; # To mark begin of deleted text passage
my $DELCLOSE='}'; # To mark end of deleted text passage
my $DELCMDOPEN='%DIFDELCMD < '; # To mark begin of deleted commands (must begin with %, i.e., be a comment
my $DELCMDCLOSE="%%%\n"; # To mark end of deleted commands (must end with a new line)
my $AUXCMD='%DIFAUXCMD' ; # follows auxiliary commands put in by latexdiff to make difference file legal
# auxiliary commands must be on a line of their own
my $DELCOMMENT='DIF < '; # To mark deleted comment line
# main local variables:
my @TEXTCMDLIST=(); # array containing patterns of commands with text arguments
my @TEXTCMDEXCL=(); # array containing patterns of commands without text arguments (if a pattern
# matches both TEXTCMDLIST and TEXTCMDEXCL it is excluded)
my @CONTEXT1CMDLIST=(); # array containing patterns of commands with text arguments (subset of text commands),
# but which cause confusion if used out of context (e.g. \caption).
# In deleted passages, the command will be disabled but its argument is marked up
# Otherwise they behave exactly like TEXTCMD's
my @CONTEXT1CMDEXCL=(); # exclude list for above, but always empty
my @CONTEXT2CMDLIST=(); # array containing patterns of commands with text arguments, but which fail cause confusion
# if used out of context (e.g. \title). They and their arguments will be disabled in deleted
# passages
my @CONTEXT2CMDEXCL=(); # exclude list for above, but always empty
my @SAFECMDLIST=(); # array containing patterns of safe commands (which do not break when in the argument of DIFadd or DIFDEL)
my @SAFECMDEXCL=();
my ($i,$j,$l);
my ($old,$new);
my ($line);
my ($newpreamble,$oldpreamble);
my (@newpreamble,@oldpreamble,@diffpreamble,@diffbody);
my ($latexdiffpreamble);
my ($oldbody, $newbody, $diffbo);
my ($oldpost, $newpost);
my ($diffall);
# Option names
my ($type,$subtype,$floattype,$config,$preamblefile,$encoding,
$showpreamble,$showsafe,$showtext,$showconfig,$showall,
$replacesafe,$appendsafe,$excludesafe,
$replacetext,$appendtext,$excludetext,
$replacecontext1,$appendcontext1,
$replacecontext2,$appendcontext2,
$help,$verbose,$version,$ignorewarnings,$allowspaces,$flatten,$debug);
my (@configlist,
@appendsafelist,@excludesafelist,
@appendtextlist,@excludetextlist,
@appendcontext1list,@appendcontext2list,
@packagelist);
my ($assign,@config);
# Hash where keys corresponds to the names of all included packages (including the documentclass as another package
# the optional arguments to the package are the values of the hash elements
my ($pkg,%packages);
# Defaults
$type='UNDERLINE';
$subtype='SAFE';
$floattype='FLOATSAFE';
$verbose=0;
$debug=1;
# define character properties
sub IsNonAsciiPunct { return <<'END' # Unicode punctuation but excluding ASCII punctuation
+utf8::IsPunct
-utf8::IsASCII
END
}
sub IsNonAsciiS { return <<'END' # Unicode symbol but excluding ASCII
+utf8::IsS
-utf8::IsASCII
END
}
my %verbhash;
Getopt::Long::Configure('bundling');
GetOptions('type|t=s' => \$type,
'subtype|s=s' => \$subtype,
'floattype|f=s' => \$floattype,
'config|c=s' => \@configlist,
'preamble|p=s' => \$preamblefile,
'encoding|e=s' => \$encoding,
'exclude-safecmd|A=s' => \@excludesafelist,
'replace-safecmd=s' => \$replacesafe,
'append-safecmd|a=s' => \@appendsafelist,
'exclude-textcmd|X=s' => \@excludetextlist,
'replace-textcmd=s' => \$replacetext,
'append-textcmd|x=s' => \@appendtextlist,
'replace-context1cmd=s' => \$replacecontext1,
'append-context1cmd=s' => \@appendcontext1list,
'replace-context2cmd=s' => \$replacecontext2,
'append-context2cmd=s' => \@appendcontext2list,
'show-preamble' => \$showpreamble,
'show-safecmd' => \$showsafe,
'show-textcmd' => \$showtext,
'show-config' => \$showconfig,
'show-all' => \$showall,
'packages=s' => \@packagelist,
'verbose|V' => \$verbose,
'ignore-warnings' => \$ignorewarnings,
'allow-spaces' => \$allowspaces,
'flatten' => \$flatten,
'version' => \$version,
'help|h|H' => \$help);
if ( $help ) {
usage() ;
}
if ( $version ) {
die $versionstring ;
}
print STDERR $versionstring if $verbose;
if (defined($showall)){
$showpreamble=$showsafe=$showtext=$showconfig=1;
}
# setting extra preamble commands
if (defined($preamblefile)) {
$latexdiffpreamble=join "\n",(extrapream($preamblefile),"");
} else {
$latexdiffpreamble=join "\n",(extrapream($type,$subtype,$floattype),"");
}
# setting up @SAFECMDLIST and @SAFECMDEXCL
if (defined($replacesafe)) {
init_regex_arr_ext(\@SAFECMDLIST,$replacesafe);
} else {
init_regex_arr_data(\@SAFECMDLIST, "SAFE COMMANDS");
}
foreach $appendsafe ( @appendsafelist ) {
init_regex_arr_ext(\@SAFECMDLIST, $appendsafe);
}
foreach $excludesafe ( @excludesafelist ) {
init_regex_arr_ext(\@SAFECMDEXCL, $excludesafe);
}
# Special: treat all cite commands as safe except in UNDERLINE and FONTSTRIKE mode
# (there is a conflict between citation and ulem package, see
# package documentation)
if ( uc($type) ne "UNDERLINE" && uc($type) ne "FONTSTRIKE" && uc($type) ne "CULINECHBAR" ) {
push (@SAFECMDLIST, qr/^cite.*$/);
}
# setting up @TEXTCMDLIST and @TEXTCMDEXCL
if (defined($replacetext)) {
init_regex_arr_ext(\@TEXTCMDLIST,$replacetext);
} else {
init_regex_arr_data(\@TEXTCMDLIST, "TEXT COMMANDS");
}
foreach $appendtext ( @appendtextlist ) {
init_regex_arr_ext(\@TEXTCMDLIST, $appendtext);
}
foreach $excludetext ( @excludetextlist ) {
init_regex_arr_ext(\@TEXTCMDEXCL, $excludetext);
}
# setting up @CONTEXT1CMDLIST ( @CONTEXT1CMDEXCL exist but is always empty )
if (defined($replacecontext1)) {
init_regex_arr_ext(\@CONTEXT1CMDLIST,$replacecontext1);
} else {
init_regex_arr_data(\@CONTEXT1CMDLIST, "CONTEXT1 COMMANDS");
}
foreach $appendcontext1 ( @appendcontext1list ) {
init_regex_arr_ext(\@CONTEXT1CMDLIST, $appendcontext1);
}
# setting up @CONTEXT2CMDLIST ( @CONTEXT2CMDEXCL exist but is always empty )
if (defined($replacecontext2)) {
init_regex_arr_ext(\@CONTEXT2CMDLIST,$replacecontext2);
} else {
init_regex_arr_data(\@CONTEXT2CMDLIST, "CONTEXT2 COMMANDS");
}
foreach $appendcontext2 ( @appendcontext2list ) {
init_regex_arr_ext(\@CONTEXT2CMDLIST, $appendcontext2);
}
# setting configuration variables
@config=();
foreach $config ( @configlist ) {
if (-f $config ) {
open(FILE,$config) or die ("Couldn't open configuration file $config: $!");
while (<FILE>) {
chomp;
next if /^\s*#/ || /^\s*%/ || /^\s*$/ ;
push (@config,$_);
}
close(FILE);
}
else {
# foreach ( split(",",$config) ) {
# push @config,$_;
# }
push @config,split(",",$config)
}
}
foreach $assign ( @config ) {
$assign=~ m/\s*(\w*)\s*=\s*(\S*)\s*$/ or die "Illegal assignment $assign in configuration list (must be variable=value)";
if ( $1 eq "MINWORDSBLOCK" ) { $MINWORDSBLOCK = $2; }
elsif ( $1 eq "FLOATENV" ) { $FLOATENV = $2 ; }
elsif ( $1 eq "PICTUREENV" ) { $PICTUREENV = $2 ; }
elsif ( $1 eq "MATHENV" ) { $MATHENV = $2 ; }
elsif ( $1 eq "MATHREPL" ) { $MATHREPL = $2 ; }
elsif ( $1 eq "MATHARRENV" ) { $MATHARRENV = $2 ; }
elsif ( $1 eq "MATHARRREPL" ) { $MATHARRREPL = $2 ; }
elsif ( $1 eq "ARRENV" ) { $ARRENV = $2 ; }
elsif ( $1 eq "COUNTERCMD" ) { $COUNTERCMD = $2 ; }
else { die "Unknown variable $1 in assignment.";}
}
foreach $pkg ( @packagelist ) {
map { $packages{$_}="" } split(/,/,$pkg) ;
}
if ($showpreamble) {
print "\nPreamble commands:\n";
print $latexdiffpreamble ;
}
if ($showsafe) {
print "\nCommands safe within scope of $ADDOPEN $ADDCLOSE and $DELOPEN $DELCLOSE (unless excluded):\n";
print_regex_arr(@SAFECMDLIST);
print "\nCommands not safe within scope of $ADDOPEN $ADDCLOSE and $DELOPEN $DELCLOSE :\n";
print_regex_arr(@SAFECMDEXCL);
}
if ($showtext) {
print "\nCommands with last argument textual (unless excluded) and safe in every context:\n";
print_regex_arr(@TEXTCMDLIST);
print "\nContext1 commands (last argument textual, command will be disabled in deleted passages, last argument will be shown as plain text):\n";
print_regex_arr(@CONTEXT1CMDLIST);
print "\nContext2 commands (last argument textual, command ant its argument will be disabled in deleted passages):\n";
print_regex_arr(@CONTEXT2CMDLIST);
print "\nExclude list of Commands with last argument not textual (overrides patterns above):\n";
print_regex_arr(@TEXTCMDEXCL);
}
if ($showconfig) {
print "Configuration variables:\n";
print "MINWORDSBLOCK=$MINWORDSBLOCK\n";
print "FLOATENV=$FLOATENV\n";
print "PICTUREENV=$PICTUREENV\n";
print "MATHENV=$MATHENV\n";
print "MATHREPL=$MATHREPL\n";
print "MATHARRENV=$MATHARRENV\n";
print "MATHARRREPL=$MATHARRREPL\n";
print "ARRENV=$ARRENV\n";
print "COUNTERCMD=$COUNTERCMD\n";
}
if ($showconfig || $showtext || $showsafe || $showpreamble) {
exit 0; }
if ( @ARGV != 2 ) {
print STDERR "2 and only 2 non-option arguments required. Write latexdiff -h to get help\n";
exit(2);
}
# Are extra spaces between command arguments permissible?
my $extraspace;
if ($allowspaces) {
$extraspace='\s*';
} else {
$extraspace='';
}
# append context lists to text lists (as text property is implied)
push @TEXTCMDLIST, @CONTEXT1CMDLIST;
push @TEXTCMDLIST, @CONTEXT2CMDLIST;
# Patterns. These are used by some of the subroutines, too
# I can only define them down here because value of extraspace depends on an option
my $pat0 = '(?:[^{}]|\\\{|\\\})*';
my $pat1 = '(?:[^{}]|\\\{|\\\}|\{'.$pat0.'\})*';
my $pat2 = '(?:[^{}]|\\\{|\\\}|\{'.$pat1.'\})*'; #
my $pat3 = '(?:[^{}]|\\\{|\\\}|\{'.$pat2.'\})*';
my $pat4 = '(?:[^{}]|\\\{|\\\}|\{'.$pat3.'\})*';
my $brat0 = '(?:[^\[\]]|\\\[|\\\])*';
my $quotemarks = '(?:\'\')|(?:\`\`)';
my $punct='[0.,\/\'\`:;\"\?\(\)\[\]!~\p{IsNonAsciiPunct}\p{IsNonAsciiS}]';
my $number='-?\d*\.\d*';
my $mathpunct='[+=<>\-\|]';
my $and = '&';
my $coords= '[\-.,\s\d]*';
# word: sequence of letters or accents followed by letter
my $word='(?:[-\w\d*]|\\\\[\"\'\`~^][A-Za-z\*])+';
my $cmdleftright='\\\\(?:left|right)\s*(?:[()\[\]|]|\\\\(?:[|{}]|\w+))';
my $cmdoptseq='\\\\[\w\d\*]+'.$extraspace.'(?:(?:\['.$brat0.'\]|\{'. $pat4 . '\}|\(' . $coords .'\))'.$extraspace.')*';
my $oneletcmd='\\\\.(?:\['.$brat0.'\]|\{'. $pat4 . '\})*';
my $math='\$(?:[^$]|\\\$)*?\$|\\\\[(].*?\\\\[)]';
# my $math='\$(?:[^$]|\\\$)*\$';
my $comment='%.*?\n';
my $pat=qr/(?:\A\s*)?(?:${and}|${quotemarks}|${number}|${word}|$cmdleftright|${cmdoptseq}|${math}|${oneletcmd}|${comment}|${punct}|${mathpunct}|\{|\})\s*/ ;
# now we are done setting up and can start working
my ($oldfile, $newfile) = @ARGV;
$encoding=guess_encoding($newfile) unless defined($encoding);
$encoding = "utf8" if $encoding =~ m/^utf8/i ;
if (lc($encoding) eq "utf8" ) {
binmode(STDOUT, ":utf8");
binmode(STDERR, ":utf8");
}
$old=read_file_with_encoding($oldfile,$encoding);
$new=read_file_with_encoding($newfile,$encoding);
# reset time
exetime(1);
($oldpreamble,$oldbody,$oldpost)=splitdoc($old,'\\\\begin\{document\}','\\\\end\{document\}');
($newpreamble,$newbody,$newpost)=splitdoc($new,'\\\\begin\{document\}','\\\\end\{document\}');
if ($flatten) {
$oldbody=flatten($oldbody,$oldpreamble,$oldfile,$encoding);
$newbody=flatten($newbody,$newpreamble,$newfile,$encoding);
}
if ( length $oldpreamble && length $newpreamble ) {
@oldpreamble = split /\n/, $oldpreamble;
@newpreamble = split /\n/, $newpreamble;
%packages=list_packages(@newpreamble) unless %packages;
if (defined $packages{"hyperref"} ) {
print STDERR "hyperref package detected.\n" if $verbose ;
$latexdiffpreamble =~ s/\{\\DIFadd\}/{\\DIFaddtex}/g;
$latexdiffpreamble =~ s/\{\\DIFdel\}/{\\DIFdeltex}/g;
$latexdiffpreamble .= join "\n",(extrapream("HYPERREF"),"");
}
# insert dummy first line such that line count begins with line 1 (rather than perl's line 0) - just so that line numbers inserted by linediff are correct
unshift @newpreamble,'';
unshift @oldpreamble,'';
print STDERR "Differencing preamble.\n" if $verbose;
@diffpreamble = linediff(\@oldpreamble, \@newpreamble);
# remove dummy line again
shift @diffpreamble;
push @diffpreamble,$latexdiffpreamble;
push @diffpreamble,'\begin{document}';
}
elsif ( !length $oldpreamble && !length $newpreamble ) {
@diffpreamble=();
} else {
print STDERR "Either both texts must have preamble or neither text must have the preamble.\n";
exit(2);
}
if (defined $packages{"amsmath"} ) {
print STDERR "amsmath package detected.\n" if $verbose ;
$MATHARRREPL='align*';
}
print STDERR "Preprocessing body. " if $verbose;
my ($oldleadin,$newleadin)=preprocess($oldbody,$newbody);
# run difference algorithm
@diffbody=bodydiff($oldbody, $newbody);
$diffbo=join("",@diffbody);
print STDERR "(",exetime()," s)\n","Postprocessing body. \n " if $verbose;
postprocess($diffbo);
$diffall =join("\n",@diffpreamble) ;
$diffall .= "$newleadin$diffbo" ;
$diffall .= "\\end{document}$newpost" if length $newpreamble ;
if ( lc($encoding) ne "utf8" && lc($encoding) ne "ascii" ) {
print STDERR "Encoding output file to $encoding\n" if $verbose;
$diffall=Encode::encode($encoding,$diffall);
binmode STDOUT;
}
print $diffall;
print STDERR "(",exetime()," s)\n","Done.\n" if $verbose;
## guess_encoding(filename)
## reads the first 20 lines of filename and looks for call of inputenc package
## if found, return the option of this package (encoding), otherwise return ascii
sub guess_encoding {
my ($filename)=@_;
my ($i,$enc);
open (FH, $filename) or die("Couldn't open $filename: $!");
$i=0;
while (<FH>) {
next if /^\s*%/; # skip comment lines
if (m/\\usepackage\[(\w*?)\]\{inputenc\}/) {
close(FH);
return($1);
}
last if (++$i > 20 ); # scan at most 20 non-comment lines
}
close(FH);
return("ascii");
}
sub read_file_with_encoding {
my ($output);
my ($filename, $encoding) = @_;
if (lc($encoding) eq "utf8" ) {
open (FILE, "<:utf8",$filename) or die("Couldn't open $filename: $!");
local $/ ; # locally set record operator to undefined, ie. enable whole-file mode
$output=<FILE>;
} elsif ( lc($encoding) eq "ascii") {
open (FILE, $filename) or die("Couldn't open $filename: $!");
local $/ ; # locally set record operator to undefined, ie. enable whole-file mode
$output=<FILE>;
} else {
require Encode;
open (FILE, "<",$filename) or die("Couldn't open $filename: $!");
local $/ ; # locally set record operator to undefined, ie. enable whole-file mode
$output=<FILE>;
print STDERR "Converting $filename from $encoding to utf8\n" if $verbose;
$output=Encode::decode($encoding,$output);
}
close FILE;
return $output;
}
# %packages=list_packages(@preamble)
# scans the arguments for \documentclass and \usepackage statements and constructs a hash
# whose keys are the included packages, and whose values are the associated optional arguments
sub list_packages {
my (@preamble)=@_;
my %packages=();
foreach $line ( @preamble ) {
# get rid of comments
$line=~s/(?<!\\)%.*$// ;
if ( $line =~ m/\\(?:documentclass|usepackage)(?:\[(.+?)\])?\{(.*?)\}/ ) {
# print STDERR "Found something: |$line|\n";
if (defined($1)) {
$packages{$2}=$1;
} else {
$packages{$2}="";
}
}
}
return (%packages);
}
# flatten($text,$preamble,$filename,$encoding)
# expands \input and \include commands within text
# premable is scanned for includeonly commands