-
Notifications
You must be signed in to change notification settings - Fork 0
/
latexdiff-1.1.0-so.pl
executable file
·4281 lines (3631 loc) · 161 KB
/
latexdiff-1.1.0-so.pl
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/env perl
##!/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-12 F J Tilmann (tilmann@gfz-potsdam.de)
#
# Repository/issue tracker: https://github.com/ftilmann/latexdiff
# CTAN page: http://www.ctan.org/tex-archive/support/latexdiff
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.
#
# Detailed usage information at the end of the file
#
# ToDo:
# DONE
#
# Version 1.1.0
# - treat diacritics (\",\', etc) as safe commands
# - treat \_ and \& correctly as safe commands, even if used without spacing to the next word
# - Add a BOLD markup type that sets added text in bold face (Contribution by Victor Zabalza via pull request )
# - add append-mboxsafecmd list option to be able to specify special safe commands which need to be surrounded by mbox to avoid breaking (mostly this is needed with ulem package)
# - support for siunitx and cleveref packages: protect \SI command in siunitx package and \cref,\Cref{range}{*} in cleveref packages (thanks to Stefan Pinnow for testing)
# - experimental support for chemformula, mhchem packages: define \ch and \ce in packages as safe (but not \ch,\cee in equation array environments) - these unfortunately will not be marked up (thanks to Stefan Pinnow for testing)
# - bug fix: packages identified correctly even if \usepackage command options extend over several lines (previously \usepackage command needed to be fully contained in one line)
# - new subtype ONLYCHANGEDPAGE outputs only changed pages (might not work well for floating material)
# - new subtype ZLABEL operates similarly to LABEL but uses absolute page numbers (needs zref package)
# - undocumented option --debug/--nodebug to override default setting for debug mode (Default: 0 for release version, 1: for development version
#
# Version 1.0.4
# - introduce list UNSAFEMATHCMD, which holds list of commands which cannot be marked up with \DIFadd or \DIFdel commands (only relevant for WHOLE and COARSE math markup modes)
# - new subtype LABEL which gives each change a label. This can later be used to only display pages where changes
# have been made (instructions for that are put as comments into the diff'ed file) inspired by answer on http://tex.stackexchange.com/questions/166049/invisible-markers-in-pdfs-using-pdflatex
# - Configuration variables take into accout some commands from additional packages:
# tikzpicture environment now treated as PICTUREENV, and \smallmatrix in ARRENV (amsmath)
# - --flatten: support for \subfile command (subfiles package) (in response to http://tex.stackexchange.com/questions/167620/latexdiff-with-subfiles )
# - --flatten: \bibliography commands expand if corresponding bbl file present
# - angled bracket optional commands now parsed correctly (patch #3570) submitted by Dave Kleinschmidt (thanks)
# - \RequirePackage now treated as synonym of \usepackage with respect to setting packages
# - special rules for apacite package (redefine citation commands)
# - recognise /dev/null as 'file-like' arguments for --preamble and --config options
# - fix units package incompatibility with ulem for text maths statements $ ..$ (thanks to Stuart Prescott for reporting this)
# - amsmath environment cases treated correctly (Bug fix #19029) (thanks to Jalar)
# - {,} in comments no longer confuse latexdiff (Bug fix #19146)
# - \% in one-letter sub/Superscripts was not converted correctly
#
# Version 1.0.3
# - fix bug in add_safe_commands that made latexdiff hang on DeclareMathOperator
# command in preamble
# - \(..\) inline math expressions were not parsed correctly, if they contained a linebreak
# - applied patch contributed by tomflannaghan via Berlios: [ Patch #3431 ] Adds correct handling of \left< and \right>
# - \$ is treated correctly as a literal dollar sign (thanks to Reed Cartwright and Joshua Miller for reporting this bug
# and sketching out the solution)
# - \^ and \_ are correctly interpreted as accent and underlined space, respectively, not as superscript of subscript
# (thanks to Wail Yahyaoui for pointing out this bug)
#
# Version 1.0.1 - treat \big,\bigg etc. equivalently to \left and
# \right - include starred version in MATHENV - apply
# - flatten recursively and --flatten expansion is now
# aware of comments (thanks to Tim Connors for patch)
# - Change to post-processing for more reliability for
# deleted math environments
# - On linux systems, recognise and remove DOS style newlines
# - Provide markup for some special preamble commands (\title,
# \author,\date,
# - configurable by setting context2cmd
# - for styles using ulem package, remove \emph and \text.. from list of
# safe commands in order to allow linebreaks within the
# highlighted sections.
# - for ulem style, now show citations by enclosing them in \mbox commands.
# This unfortunately implies linebreaks within citations no longer function,
# so this functionality can be turned off (Option --disable-citation-markup).
# With --enable-citation-markup, the mbox markup is forced for other styles)
# - new substyle COLOR. This is particularly useful for marking up citations
# and some special post-processing is implemented to retain cite
# commands in deleted blocks.
# - four different levels of math-markup
# - Option --driver for choosing driver for modes employing changebar package
# - accept \\* as valid command (and other commands of form \.*). Also accept
# \<nl> (backslashed newline)
# - some typo fixes, include commands defined in preamble as safe commands
# (Sebastian Gouezel)
# - include compared filenames as comments as line 2 and 3 of
# the preamble (can be modified with option --label, and suppressed with
# --no-label), option --visible-label to show files in generated pdf or dvi
# at the beginning of main document
#
# 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 (tilmann@esc.cam.ac.uk)
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, <mario@wolczko.com>
# by Ned Konz, perl@bike-nomad.com
# 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 warnings;
use utf8 ;
my ($algodiffversion)=split(/ /,$Algorithm::Diff::VERSION);
my ($versionstring)=<<EOF ;
This is LATEXDIFF 1.1.0 (Algorithm::Diff $Algorithm::Diff::VERSION, Perl $^V)
(c) 2004-2015 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|tikzpicture|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|alignat|gather|multline|flalign)[*]?' ; # Environments turning on eqnarray math mode
my $MATHARRREPL='eqnarray*'; # Environment introducing deleted maths blocks
my $ARRENV='(?:array|[pbvBV]?matrix|smallmatrix|cases|split)'; # Environments 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|chapter|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
my @UNSAFEMATHCMD=('qedhere'); # Commands which are definitely unsafe for marking up (amsmath qedhere only tested to not work with UNDERLINE markup)
my $MBOXINLINEMATH=0; # if set to 1 then surround marked-up inline maths expression with \mbox ( to get around compatibility
# problems between some maths packages and ulem package
# 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 or 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 @MATHTEXTCMDLIST=(); # treat like textcmd. If a textcmd is in deleted or added block, just wrap the
# whole content with \DIFadd or \DIFdel irrespective of content. This functionality
# is useful for pseudo commands \MATHBLOCK.. into which math environments are being
# transformed
my @MATHTEXTCMDEXCL=(); #
# Note I need to declare this with "our" instead of "my" because later in the code I have to "local"ise these
our @SAFECMDLIST=(); # array containing patterns of safe commands (which do not break when in the argument of DIFadd or DIFDEL)
our @SAFECMDEXCL=();
my @MBOXCMDLIST=(); # patterns for commands which are in principle safe but which need to be surrounded by an \mbox
my @MBOXCMDEXCL=(); # all the patterns in MBOXCMDLIST will be appended to SAFECMDLIST
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,$nolabel,$visiblelabel,
$showpreamble,$showsafe,$showtext,$showconfig,$showall,
$replacesafe,$appendsafe,$excludesafe,
$replacetext,$appendtext,$excludetext,
$replacecontext1,$appendcontext1,
$replacecontext2,$appendcontext2,
$help,$verbose,$driver,$version,$ignorewarnings,
$enablecitmark,$disablecitmark,$allowspaces,$flatten,$debug,$earlylatexdiffpreamble); ###$disablemathmark,
my ($mboxsafe);
# MNEMNONICS for mathmarkup
my $mathmarkup;
use constant {
OFF => 0,
WHOLE => 1,
COARSE => 2,
FINE => 3
};
my ($mboxcmd);
my (@configlist,@labels,
@appendsafelist,@excludesafelist,
@appendmboxsafelist,@excludemboxsafelist,
@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
$mathmarkup=COARSE;
$verbose=0;
# output debug and intermediate files, set to 0 in final distribution
$debug=0;
# insert preamble directly after documentclass - experimental feature, set to 0 in final distribution
# Note that this failed with mini example (or other files, where packages used in latexdiff preamble
# are called again with incompatible options in preamble of resulting file)
$earlylatexdiffpreamble=0;
# 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,
'label|L=s' => \@labels,
'no-label' => \$nolabel,
'visible-label' => \$visiblelabel,
'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,
'exclude-mboxsafecmd=s' => \@excludemboxsafelist,
'append-mboxsafecmd=s' => \@appendmboxsafelist,
'show-preamble' => \$showpreamble,
'show-safecmd' => \$showsafe,
'show-textcmd' => \$showtext,
'show-config' => \$showconfig,
'show-all' => \$showall,
'packages=s' => \@packagelist,
'allow-spaces' => \$allowspaces,
'math-markup=s' => \$mathmarkup,
'enable-citation-markup|enforce-auto-mbox' => \$enablecitmark,
'disable-citation-markup|disable-auto-mbox' => \$disablecitmark,
'verbose|V' => \$verbose,
'ignore-warnings' => \$ignorewarnings,
'driver=s'=> \$driver,
'flatten' => \$flatten,
'version' => \$version,
'help|h|H' => \$help,
'debug!' => \$debug );
if ( $help ) {
usage() ;
}
if ( $version ) {
die $versionstring ;
}
print STDERR $versionstring if $verbose;
if (defined($showall)){
$showpreamble=$showsafe=$showtext=$showconfig=1;
}
# Default types
$type='UNDERLINE' unless defined($type);
$subtype='SAFE' unless defined($subtype);
# set floattype to IDENTICAL for LABEL and ONLYCHANGEDPAGE subtype, unless it has been set explicitly on the command line
$floattype=($subtype eq 'LABEL' || $subtype eq 'ONLYCHANGEDPAGE') ? 'IDENTICAL' : 'FLOATSAFE' unless defined($floattype);
if ( $subtype eq 'LABEL' ) {
print STDERR "Note that LABEL subtype is deprecated. If possible, use ZLABEL instead (requires zref package)";
}
if (defined($mathmarkup)) {
$mathmarkup=~tr/a-z/A-Z/;
if ( $mathmarkup eq 'OFF' ){
$mathmarkup=OFF;
} elsif ( $mathmarkup eq 'WHOLE' ){
$mathmarkup=WHOLE;
} elsif ( $mathmarkup eq 'COARSE' ){
$mathmarkup=COARSE;
} elsif ( $mathmarkup eq 'FINE' ){
$mathmarkup=FINE;
} elsif ( $mathmarkup !~ m/^[0123]$/ ) {
die "Illegal value: ($mathmarkup) for option--math-markup. Possible values: OFF,WHOLE,COARSE,FINE,0- ";
}
# else use numerical value
}
# setting extra preamble commands
if (defined($preamblefile)) {
$latexdiffpreamble=join "\n",(extrapream($preamblefile),"");
} else {
$latexdiffpreamble=join "\n",(extrapream($type,$subtype,$floattype),"");
}
if ( defined($driver) ) {
# for changebar only
$latexdiffpreamble=~s/\[dvips\]/[$driver]/sg;
}
# 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);
}
# setting up @MBOXCMDLIST and @MBOXCMDEXCL
foreach $mboxsafe ( @appendmboxsafelist ) {
init_regex_arr_ext(\@MBOXCMDLIST, $mboxsafe);
}
foreach $mboxsafe ( @excludemboxsafelist ) {
init_regex_arr_ext(\@MBOXCMDEXCL, $mboxsafe);
}
# 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 || lc $config eq '/dev/null' ) {
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.";}
}
if ( $mathmarkup == COARSE || $mathmarkup == WHOLE ) {
push(@MATHTEXTCMDLIST,qr/^MATHBLOCK(?:$MATHENV|$MATHARRENV|SQUAREBRACKET)$/);
}
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 and 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;
push @TEXTCMDLIST, @MATHTEXTCMDLIST if $mathmarkup==COARSE;
# internal additions to SAFECMDLIST
push(@SAFECMDLIST, qr/^QLEFTBRACE$/, qr/^QRIGHTBRACE$/);
# 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 $pat5 = '(?:[^{}]|\{'.$pat4.'\})*';
my $pat6 = '(?:[^{}]|\{'.$pat5.'\})*';
my $brat0 = '(?:[^\[\]]|\\\[|\\\])*';
my $abrat0 = '(?:[^<>])*';
my $quotemarks = '(?:\'\')|(?:\`\`)';
my $punct='[0.,\/\'\`:;\"\?\(\)\[\]!~\p{IsNonAsciiPunct}\p{IsNonAsciiS}]';
my $number='-?\d*\.\d*';
my $mathpunct='[+=<>\-\|]';
my $and = '&';
my $coords= '[\-.,\s\d]*';
# quoted underscore - this needs special treatment as perl treats _ as a letter (\w) but latex does not
# such that a\_b is interpreted as a{\_}b by latex but a{\_b} by perl
my $quotedunderscore='\\\\_';
# word: sequence of letters or accents followed by letter
my $word='(?:[-\w\d*]|\\\\[\"\'\`~^][A-Za-z\*])+';
my $cmdleftright='\\\\(?:left|right|[Bb]igg?[lrm]?|middle)\s*(?:[<>()\[\]|]|\\\\(?:[|{}]|\w+))';
my $cmdoptseq='\\\\[\w\d\*]+'.$extraspace.'(?:(?:<'.$abrat0.'>|\['.$brat0.'\]|\{'. $pat6 . '\}|\(' . $coords .'\))'.$extraspace.')*';
my $backslashnl='\\\\\n';
my $oneletcmd='\\\\.\*?(?:\['.$brat0.'\]|\{'. $pat6 . '\})*';
my $math='\$(?:[^$]|\\\$)*?\$|\\\\[(](?:.|\n)*?\\\\[)]';
## the current maths command cannot cope with newline within the math expression