forked from ftilmann/latexdiff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlatexdiff
More file actions
executable file
·5597 lines (4810 loc) · 242 KB
/
Copy pathlatexdiff
File metadata and controls
executable file
·5597 lines (4810 loc) · 242 KB
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-20 F J Tilmann (tilmann@gfz-potsdam.de)
#
# Repository/issue tracker: https://github.com/ftilmann/latexdiff
# CTAN page: http://www.ctan.org/pkg/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 (ideas):
###
### - add possibility to store configuration options for latexdiff in a file rather than as options
### - use kdiff3 as a merge tool
### - make style that allows (forward and backjumping with hyperref)
### - --flatten option only expands first including command per line if there is more than one
### - move --show-xxx options so that they are also capable of showing preamble (and commands) after all modificationsbased on source file packages
### - change meaning of --packages option such that this packages are used in addition of automatically detected packages (possibly introduce option --only-packages that overrides automatic choices completely
#
# Version 1.3.2
# - extend CUSTOMDIFCMD related postprocessing to deal properly with multiline commands, or a sequence of several commands in the same line (see github issue #204)
# - fix a bug in biblatex mode, which prevented proper processing of modified \textcite (see: https://tex.stackexchange.com/questions/555157/latexdiff-and-biblatex-citation-commands)
# - -h string fix: add -driver option
# replace default driver dvips->pdftex
# - fix issue #206 affecting proper markup of text commands which are not safe cmd's at the same time and have multiple arguments
# - fix issue #210 by adding \eqref (amsmath package) to the list of safe commands
# - fix bug reported in issue #168 mangled verbatim line environment
# - fix bug reported in issue #218 by replacing \hspace{0pt} after \mbox{..} auxiliary commands with \hskip0pt.
#
# Version 1.3.1.1
# - remove spurious \n to fix error: Unknown regexp modifier "/n" at .../latexdiff line 1974, near "=~ " (see github issue #201)
#
# Version 1.3.1
# Bug fixes:
# - remove some uninitialised variable $2 warnings in string substitution in flatten function in case included file is not found
# - add minimal postprocessing to diff processing of preamble commands (replace \RIGHTBRACE by \} )
# - pre-processing: replace (contributed) routine take_comments_and_enter_from_frac() with take_comments_and_newline_from_frac(), which does the same thing
# (remove whitespace characters and comments between the argument of \frac commands) in an easier and more robust way. In addition, it
# will replace commands like \frac12 with \frac{1}{2} as pre-processing step. Fixes issue #184
# - add "intertext" to list of unsafe math commands @UNSAFEMATHCMD . Fixes issue #179
# - provide citation command patterns for biblatex and protect them with mbox'es. Fixes issue #199
# - hardcode number of parameters for \href and \url commands to allow spaces between commands and arguments even if --allow-spaces option is not used (this
# is needed because some bibliography styles add such in-command-sequence spaces) Fixes issues: #178 #198
# - bibitem is now kept even in deleted blocks such that deleted references show up properly (this implies that the actual numbers in numerical referencing schemes will change)
# (this is implemented by introducing a new class of commands KEEPCMD , which are kept as is in deleted environments (no effect in added environments). Currently
# \bibitem is hardwired to be the only member of this class (fixes issue #194, #174)
# Features:
# - add some special processing for revtex bibliography commands, so that the spaces between bibliography commands \bibfield and \bibinfo and their arguments are ignored.
# (fixes issue #194, should fix #174)
#
# Version 1.3.0 (7 October 2018):
# - treat options to \documentclass as potential package names (some packages allow implicit loading of or imply selected packages
# - improved pattern matching: now allows nested angular brackets, and is no longer confused by escaped curly braces
# - improved pattern matching in COARSE mode: occasionally, the closing bracket or some other elements would be matched in an 'unnatural' way due to another sequence being more minimal in the computational sense, sometimes even causing errors due to tokens moving in or out of the scope of math environments. This is now discouraged by adding internal \DIFANCHOR commands (which are removed again in post-processing) (fixes issues reported via email by li_ruomeng .
# - verbatim and lstlisting environments are marked-up with line-by-line in a similar style to non-verbatim text (requires the listing package to be installed)
# (see new configuration variable VERBATIMLINEENV) (several issues and pull requests by jprotze)
# - --flatten: now supports \verbatiminput and \lstlistinput
# - --flatten: if file is not found, do not fail, simply warn and leave command unexpanded (inspired by issue #112). Don't warn if file name contains #[0-9] as it is then most likely an argument within a command definition rather than an actual file (applies to \input, \subfile, \include commands)
# - added to textcmds: \intertext
# - new config variable CUSTOMDIFCMD to allow defining special versions of commands in added or deleted blocks (Pull request by github user jprotze)
# - added option -no-links (mostly for use by latexdiff-vc in only-changes modes) (Pull request by github user jprotze)
# - new option --filter-script to run both input through a pre-processing script (PR jasonmccsmith #167)
# new option --no-filter-stderr to hide stderr output from filter-script (potentially dangerous, as this might hide malfunctioning of filter scripts)
# - --flatten now can deal with imports made using the import package {PR jasonmccsmith #173)
# Bug fixes:
# - pattern matching of \verb and \lstinline commands had an error which meant they would trigger on commands beginning with \verb.
# - In description environments, mark up item descriptions by effectively reating the insides of item commannds as text commands (fixes #161)
#
#
# Version 1.2.1 (22 June 2017)
# - add "DeclareOldFontCommand" to styles using \bf or \sf old style font commands (fixies issue #92 )
# - improved markup: process lstinline commands in listings package correctly
# for styles using colour, \verb and \lstinline arguments are marked up with colour (blue for added, red for deleted)
# - bug fix: protecting inline math expressions for mbox did not work as intended (see stack exchange question: http://tex.stackexchange.com/questions/359412/compiling-the-latexdiff-when-adding-a-subscript-before-a-pmatrix-environment-cau)
# - bug fix: when deleted \item commands are followed immediately by unsafe commands, they were not restored properly
# (thanks to J. Protze for pull request) (pull request #89)
# - treat lstlisting and comment as equivalent to verbatim environment
# make environments that are treated like verbatim environments configurable (config variable VERBATIMENV)
# treat lstinlne as equivalent to verb command
# partially addresses issue #38
# - refactoring: set default configuration variables in a hash, and those that correspond to lists
# - feature: option --add-to-config used to amend configuration variables, which are regex pattern lists
# - bug fix: deleted figures when endfloat package is activated
# - bug fix: alignat environment now always processed correctly (fix issues #65)
# - bug fix: avoid processing of commands as potential files in routine init_regex_arr (fix issue #70 )
# - minimal feature enhancement: treat '@' as allowed character in commands (strictly speaking requires prior \makeatletter statement, but always assuming it to be
# @ a letter if it is part of a command name will usually lead to the correct behaviour (see http://tex.stackexchange.com/questions/346651/latexdiff-and-let)
# - new feature/bug fix: --flatten option \endinput in included files now respected but only if \endinput stands right at the beginning of the line (issue #77)
# - bug fix: flatten would incorrectly attempt to process commented out \include commands (from discussion in issue #77 )
# - introduce an invisible space (\hspace{0pt} after \mbox{..} auxiliary commands (not in math mode), to allow line breaks between added and deleted citations (change should not cause adverse behaviour otherwise)
#
# Version 1.2.0:
# - highlight new and deleted figures
# - bug fix in title mark-up. Previously deleted commands in title (such as \title, \author or \date) were marked up erroneously
# - (minor) bug fixes in new 1.1.1 features: disabled label was commented out twice, additional spaces were introduced before list environment begin and end commands
# - depracation fix: left brace in RegEx now needs to be escaped
# - add type PDFCOMMENT based on issue #49 submitted by github user peci1 (Martin Pecka)
# - make utf8 the default encoding
#
# Version 1.1.1
# - patch mhchem: allow ce in equations
# - flatten now also expands \input etc. in the preamble (but not \usepackage!)
# - Better support for Japanese ( contributed by github user kshramt )
# - prevent duplicated verbatim hashes (patch contributed by github user therussianjig, issue #36)
# - disable deleted label commands (fixes issue #31)
# - introduce post-processing to reinstate most deleted environments and all needed item commands (fixes issue #1)
#
# 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
### NB Lines starting with three hashes should be removed before release
use Algorithm::Diff qw(traverse_sequences);
use Getopt::Long ;
use strict ;
use warnings;
use utf8 ;
use File::Spec ;
my ($algodiffversion)=split(/ /,$Algorithm::Diff::VERSION);
my ($versionstring)=<<EOF ;
This is LATEXDIFF 1.3.2a (Algorithm::Diff $Algorithm::Diff::VERSION, Perl $^V)
(c) 2004-2020 F J Tilmann
EOF
# Hash with defaults for configuration variables. These marked undef have default values constructed from list defined in the DATA block
# (under tag CONFIG)
my %CONFIG=(
MINWORDSBLOCK => 3, # minimum number of tokens to form an independent block
# shorter identical blocks will be merged to the previous word
SCALEDELGRAPHICS => 0.5, # factor with which deleted figures will be scaled down (i.e. 0.5 implies they are shown at half linear size)
# this is only used for --graphics-markup=BOTH option
FLOATENV => undef , # Environments in which FL variants of defined commands are used
PICTUREENV => undef , # Environments in which all change markup is removed
MATHENV => undef , # Environments turning on display math mode (code also knows about \[ and \])
MATHREPL => 'displaymath', # Environment introducing deleted maths blocks
MATHARRENV => undef , # Environments turning on eqnarray math mode
MATHARRREPL => 'eqnarray*', # Environment introducing deleted maths blocks
ARRENV => undef , # 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
COUNTERCMD => undef,
# COUNTERCMD textcmds which are associated with a counter
# If any of these commands occur in a deleted block
# they will be followed by an \addtocounter{...}{-1}
# for the associated counter such that the overall numbers
# should be the same as in the new file
LISTENV => undef , # list making environments - they will generally be kept
VERBATIMENV => undef, # Environments whose content should be treated as verbatim text and not be touched
VERBATIMLINEENV => undef, # Environments whose content should be treated as verbatim text and processed in line diff mode
CUSTOMDIFCMD => undef,# Custom dif command. Is defined in the document as a \DELcommand and \ADDcommand version to be replaced by the diff
ITEMCMD => 'item' # command marking item in a list environment
);
# Configuration variables: these have to be visible from the subroutines
my ($ARRENV,
$COUNTERCMD,
$FLOATENV,
$ITEMCMD,
$LISTENV,
$MATHARRENV,
$MATHARRREPL,
$MATHENV,
$MATHREPL,
$MINWORDSBLOCK,
$PICTUREENV,
$SCALEDELGRAPHICS,
$VERBATIMENV,
$VERBATIMLINEENV,
$CUSTOMDIFCMD
);
# my $MINWORDSBLOCK=3; # minimum number of tokens to form an independent block
# # shorter identical blocks will be merged to the previous word
# my $SCALEDELGRAPHICS=0.5; # factor with which deleted figures will be scaled down (i.e. 0.5 implies they are shown at half linear size)
# # this is only used for --graphics-markup=BOTH option
# 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='(?:aligned|gathered|multlined|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 $LISTENV='(?:itemize|description|enumerate)'; # list making environments - they will generally be kept
# my $ITEMCMD='item'; # command marking item in a list environment
my $LABELCMD='(?:label)'; # matching commands are disabled within deleted blocks - mostly useful for maths mode, as otherwise it would be fine to just not add those to SAFECMDLIST
my @UNSAFEMATHCMD=('qedhere','intertext'); # Commands which are definitely unsafe for marking up in math mode (amsmath qedhere only tested to not work with UNDERLINE markup) (only affects WHOLE and COARSE math markup modes). Note that unlike text mode (or FINE math mode0 deleted unsafe commands are not deleted but simply taken outside \DIFdel
###my $CITECMD=0 ; # \cite-type commands which need to be protected within an mbox in UNDERLINE and other modes using ulem; pattern simply designed to never match; will be overwritten later for selected styles
###my $CITE2CMD=0; # \cite-type commands which should be reinstated in deleted blocks
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
### use context2cmd list instead to define TITLECMD
###my $TITLECMD='(?:title|author|date|institute)'; # Preamble commands which contain text to be epressed by \maketitle command
# 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
# Note that for verbatim environment openings the %DIFAUXCMD cannot be placed in
# the same line as this would mean they are shown
# so the special form "%DIFAUXCMD NEXT" is used to indicate that the next line
# is an auxiliary command
# Similarly "%DIFAUXCMD LAST" would indicate the auxiliary command is in previous line (not currently used)
my $DELCOMMENT='DIF < '; # To mark deleted comment line
my $VERBCOMMENT='DIFVRB '; # to mark lines which are within a verbatim environment
# 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 @KEEPCMDLIST=( qr/^bibitem$/ ); # patterns for commands which should not be deleted in nominally delete text passages
my @KEEPCMDEXCL=();
my ($i,$j,$l);
my ($old,$new);
my ($line,$key);
my (@dumlist);
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,
$filterscript,$ignorefilterstderr,
$showpreamble,$showsafe,$showtext,$showconfig,$showall,
$replacesafe,$appendsafe,$excludesafe,
$replacetext,$appendtext,$excludetext,
$replacecontext1,$appendcontext1,
$replacecontext2,$appendcontext2,
$help,$verbose,$driver,$version,$ignorewarnings,
$enablecitmark,$disablecitmark,$allowspaces,$flatten,$nolinks,$debug,$earlylatexdiffpreamble); ###$disablemathmark,
my ($mboxsafe);
# MNEMNONICS for mathmarkup
my $mathmarkup;
use constant {
OFF => 0,
WHOLE => 1,
COARSE => 2,
FINE => 3
};
# MNEMNONICS for graphicsmarkup
my $graphicsmarkup;
use constant {
NONE => 0,
NEWONLY => 1,
BOTH => 2
};
my ($mboxcmd);
my (@configlist,@addtoconfiglist,@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,
'add-to-config=s' => \@addtoconfiglist,
'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,
'graphics-markup=s' => \$graphicsmarkup,
'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,
'filter-script=s' => \$filterscript,
'ignore-filter-stderr' => \$ignorefilterstderr,
'no-links' => \$nolinks,
'version' => \$version,
'help|h' => \$help,
'debug!' => \$debug ) or die "Use latexdiff -h to get help.\n" ;
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 "latexdiff Illegal value: ($mathmarkup) for option--math-markup. Possible values: OFF,WHOLE,COARSE,FINE,0-3\n";
}
# else use numerical value
}
# Give filterscript a default empty string
$filterscript="" unless defined($filterscript);
# 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/\[pdftex\]/[$driver]/sg;
}
# setting up @SAFECMDLIST and @SAFECMDEXCL
if (defined($replacesafe)) {
init_regex_arr_ext(\@SAFECMDLIST,$replacesafe);
} else {
init_regex_arr_data(\@SAFECMDLIST, "SAFE COMMANDS");
}
### if (defined($appendsafe)) {
foreach $appendsafe ( @appendsafelist ) {
init_regex_arr_ext(\@SAFECMDLIST, $appendsafe);
}
### }
### if (defined($excludesafe)) {
foreach $excludesafe ( @excludesafelist ) {
init_regex_arr_ext(\@SAFECMDEXCL, $excludesafe);
}
### }
# setting up @MBOXCMDLIST and @MBOXCMDEXCL
### if (defined($mboxsafelist)) {
foreach $mboxsafe ( @appendmboxsafelist ) {
init_regex_arr_ext(\@MBOXCMDLIST, $mboxsafe);
}
### }
### if (defined($excludesafe)) {
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");
}
### if (defined($appendtext)) {
foreach $appendtext ( @appendtextlist ) {
init_regex_arr_ext(\@TEXTCMDLIST, $appendtext);
}
### if (defined($excludetext)) {
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
### if (defined($config)) {
@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)
}
}
### print STDERR "configuration: |$config| , #@config#\n";
foreach $assign ( @config ) {
### print STDERR "assign:|$assign|\n";
$assign=~ m/\s*(\w*)\s*=\s*(\S*)\s*$/ or die "Illegal assignment $assign in configuration list (must be variable=value)";
exists $CONFIG{$1} or die "Unknown configuration variable $1.";
$CONFIG{$1}=$2;
}
my @addtoconfig=();
foreach $config ( @addtoconfiglist ) {
if (-f $config || lc $config eq '/dev/null' ) {
open(FILE,$config) or die ("Couldn't open addd-to-config file $config: $!");
while (<FILE>) {
chomp;
next if /^\s*#/ || /^\s*%/ || /^\s*$/ ;
push (@addtoconfig,$_);
}
close(FILE);
}
else {
# foreach ( split(",",$config) ) {
# push @addtoconfig,$_;
# }
push @addtoconfig,split(",",$config)
}
}
# initialise default lists from DATA
# for those configuration variables, which have not been set explicitly, initiate from list in document
foreach $key ( keys(%CONFIG) ) {
if (!defined $CONFIG{$key}) {
@dumlist=();
init_regex_arr_data(\@dumlist,"$key CONFIG");
$CONFIG{$key}=join(";",@dumlist)
}
}
### print STDERR "configuration: |$config| , #@config#\n";
foreach $assign ( @addtoconfig ) {
###print STDERR "assign:|$assign|\n";
$assign=~ m/\s*(\w*)\s*=\s*(\S*)\s*$/ or die "Illegal assignment $assign in configuration list (must be variable=value)";
exists $CONFIG{$1} or die "Unknown configuration variable $1.";
$CONFIG{$1}.=";$2";
}
# Map from hash to variables (we do this to have more concise code later, change from comma-separated list)
foreach ( keys(%CONFIG) ) {
if ( $_ eq "MINWORDSBLOCK" ) { $MINWORDSBLOCK = $CONFIG{$_}; }
elsif ( $_ eq "FLOATENV" ) { $FLOATENV = liststringtoregex($CONFIG{$_}) ; }
elsif ( $_ eq "ITEMCMD" ) { $ITEMCMD = $CONFIG{$_} ; }
elsif ( $_ eq "LISTENV" ) { $LISTENV = liststringtoregex($CONFIG{$_}) ; }
elsif ( $_ eq "PICTUREENV" ) { $PICTUREENV = liststringtoregex($CONFIG{$_}) ; }
elsif ( $_ eq "MATHENV" ) { $MATHENV = liststringtoregex($CONFIG{$_}) ; }
elsif ( $_ eq "MATHREPL" ) { $MATHREPL = $CONFIG{$_} ; }
elsif ( $_ eq "MATHARRENV" ) { $MATHARRENV = liststringtoregex($CONFIG{$_}) ; }
elsif ( $_ eq "MATHARRREPL" ) { $MATHARRREPL = $CONFIG{$_} ; }
elsif ( $_ eq "ARRENV" ) { $ARRENV = liststringtoregex($CONFIG{$_}) ; }
elsif ( $_ eq "VERBATIMENV" ) { $VERBATIMENV = liststringtoregex($CONFIG{$_}) ; }
elsif ( $_ eq "VERBATIMLINEENV" ) { $VERBATIMLINEENV = liststringtoregex($CONFIG{$_}) ; }
elsif ( $_ eq "CUSTOMDIFCMD" ) { $CUSTOMDIFCMD = liststringtoregex($CONFIG{$_}) ; }
elsif ( $_ eq "COUNTERCMD" ) { $COUNTERCMD = liststringtoregex($CONFIG{$_}) ; }
elsif ( $_ eq "SCALEDELGRAPHICS" ) { $SCALEDELGRAPHICS = $CONFIG{$_} ; }
else { die "Unknown configuration variable $_.";}
}
if ( $mathmarkup == COARSE || $mathmarkup == WHOLE ) {
push(@MATHTEXTCMDLIST,qr/^MATHBLOCK(?:$MATHENV|$MATHARRENV|SQUAREBRACKET)$/);
}
### if ( $disablemathmark ) {
### $PICTUREENV="(?:$PICTUREENV)|(?:$MATHENV)|(?:$MATHARRENV)|SQUAREBRACKET";
### $MATHENV="";
### $MATHARRENV="";
### }
foreach $pkg ( @packagelist ) {
map { $packages{$_}="" } split(/,/,$pkg) ;
}
if ($showconfig || $showtext || $showsafe || $showpreamble) {
show_configuration();
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.'\})*';
### 0.6: Use preprocessing to suppress \{ and \}, so no longer need to account for this in patterns
### my $pat0 = '(?:[^{}])*';
### my $pat1 = '(?:[^{}]|\{'.$pat0.'\})*';
### my $pat2 = '(?:[^{}]|\{'.$pat1.'\})*';
### my $pat3 = '(?:[^{}]|\{'.$pat2.'\})*';
### my $pat4 = '(?:[^{}]|\{'.$pat3.'\})*';
### my $pat5 = '(?:[^{}]|\{'.$pat4.'\})*';
### my $pat6 = '(?:[^{}]|\{'.$pat5.'\})*';
my $pat0 = '(?:[^{}])*';
my $pat_n = $pat0;
# if you get "undefined control sequence MATHBLOCKmath" error, increase the maximum value in this loop
for (my $i_pat = 0; $i_pat < 20; ++$i_pat){
$pat_n = '(?:[^{}]|\{'.$pat_n.'\}|\\\\\{|\\\\\})*';
# Actually within the text body, quoted braces are replaced in pre-processing. The only place where
# the last part of the pattern matters is when processing the arguments of context2cmds in the preamble
# and these contain a \{ or \} combination, probably rare.
# It should thus be fine to use the simpler version below.
### $pat_n = '(?:[^{}]|\{'.$pat_n.'\})*';
}
my $brat0 = '(?:[^\[\]]|\\\[|\\\])*';
my $brat_n = $brat0;
for (my $i_pat = 0; $i_pat < 4; ++$i_pat){
$brat_n = '(?:[^\[\]]|\['.$brat_n.'\]|\\\[|\\\])*';
### $brat_n = '(?:[^\[\]]|\['.$brat_n.'\])*'; # Version not taking into account escaped \[ and \]
}
my $abrat0 = '(?:[^<>])*';
###print STDERR "DEBUG pat1 $pat1\n pat2 $pat_n\n";
my $quotemarks = '(?:\'\')|(?:\`\`)';
my $punct='[0.,\/\'\`:;\"\?\(\)\[\]!~\p{IsNonAsciiPunct}\p{IsNonAsciiS}]';
my $number='-?\d*\.\d*';
my $mathpunct='[+=<>\-\|]';
my $and = '&';
### my $spacecmd = '\\\\\040';
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_ja='\p{Han}+|\p{InHiragana}+|\p{InKatakana}+';
my $word='(?:' . $word_ja . '|(?:(?:[-\w\d*]|\\\\[\"\'\`~^][A-Za-z\*])(?!(?:' . $word_ja . ')))+)';
# for selected commands, the number of arguments is known, and we can therefore allow spaces between command and its argument
# Note that it is still expected that the arguments are blocks marked by parentheses rather than single characters, and that intervening comments will inhibit the association
my $predefinedcmdoptseq01='\\\\(?:url|BibitemShut)\s*\s*(?:\{'. $pat_n . '\}\s*){1}'; # Commands with one non-optional argument
my $predefinedcmdoptseq12='\\\\(?:href|bibfield|bibinfo)\s*(?:\['.$brat_n.'\])?\s*(?:\{'. $pat_n . '\}\s*){2}'; # Commands with one optional and two non-optional arguments
# my $predefinedcmdoptseq11='\\\\(?:bibitem)\s*(?:\['.$brat_n.'\])?\s*(?:\{'. $pat_n . '\}\s*){1}'; # Commands with one optional and one non-optional arguments
# \bibitem in revtex styles appears to be always followed by \BibItemOpen. We bind \BibItemOpen to the bibitem (if present) in order to prevent the comparison algorithm to interpret the \BibItemOpen as an identical part of the sequence; this interpretation can lead to added and removed entries to the reference list to become mixed.
my $predefinedbibitem='\\\\(?:bibitem)\s*(?:\['.$brat_n.'\])?\s*(?:\{'. $pat_n . '\})(?:%?\s*\\\\BibitemOpen)?'; # Commands with one optional and one non-optional arguments
my $predefinedcmdoptseq='(?:'.$predefinedcmdoptseq12.'|'.$predefinedcmdoptseq01.'|'.$predefinedbibitem.')';
my $cmdleftright='\\\\(?:left|right|[Bb]igg?[lrm]?|middle)\s*(?:[<>()\[\]|\.]|\\\\(?:[|{}]|\w+))';
### my $word='(?:[-\p{IsL}*]|\\\\[\"\'\`~^][\p{IsL}A-Za-z\*])+';
# standard $cmdoptseq (default: no intrevening spaces, controlled by extraspcae) - a final open parentheses is merged to the commend if it exists to deal properly with multi-argument text command
###pre-0.3 my $cmdoptseq='\\\\[\w\d\*]+(?:\['.$brat0.'\]|\{'. $pat_n . '\}|\(' . $coords .'\))*';
### my $cmdoptseq='\\\\[\w\d\*]+'.$extraspace.'(?:(?:\['.$brat0.'\]|\{'. $pat_n . '\}|\(' . $coords .'\))'.$extraspace.')*';
my $cmdoptseq='\\\\[\w\d@\*]+'.$extraspace.'(?:(?:<'.$abrat0.'>|\['.$brat_n.'\]|\{'. $pat_n . '\}|\(' . $coords .'\))'.$extraspace.')*\{?';
# Handle tex \def macro: \def\MAKRONAME#1[#2]#3{DEFINITION}
my $defseq='\\\\def\\\\[\w\d@\*]+(?:#\d+|\[#\d+\])+(?:\{'. $pat_n . '\})?';
###pre-0.3 my $oneletcmd='(?:\\\\.|[_\^])(?:\['.$brat0.'\]|\{'. $pat_n . '\})*';
my $backslashnl='\\\\\n';
my $oneletcmd='\\\\.\*?(?:\['.$brat_n.'\]|\{'. $pat_n . '\})*';
### the commented out version is simpler but for some reason cannot cope with newline (in spite of s option) - need to include \newline explicitly
### my $math='\$(?:[^$]|\\\$)*?\$|\\\\[(].*?\\\\[)]';
my $math='\$(?:[^$]|\\\$)*?\$|\\\\[(](?:.|\n)*?\\\\[)]';
### test version (this seems to give the same results as version above)
## the current maths command cannot cope with newline within the math expression
### my $math='\$(?:[^$]|\\\$)*?\$|\\[(].*?\\[)]';
### my $math='\$(?:[^$]|\\\$)*\$';
### my $comment='%.*?\n';
my $comment='%[^\n]*\n';
my $pat=qr/(?:\A\s*)?(?:${and}|${quotemarks}|${number}|${word}|$quotedunderscore|${defseq}|$cmdleftright|${predefinedcmdoptseq}|${cmdoptseq}|${math}|${backslashnl}|${oneletcmd}|${comment}|${punct}|${mathpunct}|\{|\})\s*/ ;
# now we are done setting up and can start working
my ($oldfile, $newfile) = @ARGV;
# check for existence of input files
if ( ! -e $oldfile ) {
die "Input file $oldfile does not exist";
}
if ( ! -e $newfile ) {
die "Input file $newfile does not exist";
}
# set the labels to be included into the file
# first find out which file name is longer for correct alignment
my ($diff,$oldlabel_n_spaces,$newlabel_n_spaces);
$oldlabel_n_spaces = 0;
$newlabel_n_spaces = 0;
$diff = length($newfile) - length($oldfile);
if ($diff > 0) {
$oldlabel_n_spaces = $diff;
}
if ($diff < 0) {
$newlabel_n_spaces = abs($diff);
}
my ($oldtime,$newtime,$oldlabel,$newlabel);
if (defined($labels[0])) {
$oldlabel=$labels[0] ;
} else {
$oldtime=localtime((stat($oldfile))[9]);
$oldlabel="$oldfile " . " "x($oldlabel_n_spaces) . $oldtime;
}
if (defined($labels[1])) {
$newlabel=$labels[1] ;
} else {
$newtime=localtime((stat($newfile))[9]);
$newlabel="$newfile " . " "x($newlabel_n_spaces) . $newtime;
}
$encoding=guess_encoding($newfile) unless defined($encoding);
$encoding = "utf8" if $encoding =~ m/^utf8/i ;
###print STDERR "Encoding $encoding\n" if $verbose;
if (lc($encoding) eq "utf8" ) {
binmode(STDOUT, ":utf8");
binmode(STDERR, ":utf8");
}
# filter($text)
# Runs $text through the script provided in $filterscript argument, if set
# If not set, just returns $text unchanged.
# If flatten was set, defer filtering to flatten. flatten will run the filter
# on all incoming text prior to its own processing.
# If flatten was not set, filter each of old and new once (see just below this def)
sub filter {
my ($text)=@_;
my ($textout,$pid);
if ($filterscript ne "") {
print STDERR "Passing " . length($text) . " chars to filter script " . $filterscript . "\n" if $verbose;
if ($ignorefilterstderr) {
# If we need to capture and bury STDERR, use the Open3 version, and close CHLD_ERR below.
use IPC::Open3;
# We consume STDERR from the process, and hide it
$pid = open3(\*CHLD_IN, \*CHLD_OUT, \*CHLD_ERR, $filterscript) or die "open3() failed $!";
}
else {
# Capture STDOUT and use as our new $text. Allow STDERR to go to console.
use IPC::Open2;
$pid = open2(\*CHLD_OUT, \*CHLD_IN, $filterscript) or die "open2() failed $!";
}
# Send in $text
print CHLD_IN $text."\n"; # Adding a newline just to make sure there is one.
close CHLD_IN;
# Wait for output and gather it up
while (<CHLD_OUT>) {
$textout = $textout.$_;
}
if ($ignorefilterstderr) {
close CHLD_ERR; # Enable only if Open3 used above
}
# On the off chance a very long running and/or frequently called script is used.
waitpid( $pid, 0 );
$text = $textout;
print STDERR "Received " . length($text) . " chars after filtering\n" if $verbose;
print STDERR $text if $verbose;
}
return $text;
}
$old=read_file_with_encoding($oldfile,$encoding);
$new=read_file_with_encoding($newfile,$encoding);
if (not defined($flatten)) {
$old=filter($old);
$new=filter($new);
}
###if (lc($encoding) eq "utf8" ) {
### binmode(STDOUT, ":utf8");
### binmode(STDERR, ":utf8");
### open (OLD, "<:utf8",$oldfile) or die("Couldn't open $oldfile: $!");
### open (NEW, "<:utf8",$newfile) or die("Couldn't open $newfile: $!");
### local $/ ; # locally set record operator to undefined, ie. enable whole-file mode
### $old=<OLD>;
### $new=<NEW>;
###} elsif ( lc($encoding) eq "ascii") {
### open (OLD, $oldfile) or die("Couldn't open $oldfile: $!");
### open (NEW, $newfile) or die("Couldn't open $newfile: $!");
### local $/ ; # locally set record operator to undefined, ie. enable whole-file mode
### $old=<OLD>;
### $new=<NEW>;
###} else {
### require Encode;
### open (OLD, "<",$oldfile) or die("Couldn't open $oldfile: $!");
### open (NEW, "<",$newfile) or die("Couldn't open $newfile: $!");
### local $/ ; # locally set record operator to undefined, ie. enable whole-file mode
### $old=<OLD>;
### $new=<NEW>;
### print STDERR "Converting from $encoding to utf8\n" if $verbose;
### $old=Encode::decode($encoding,$old);
### $new=Encode::decode($encoding,$new);
###}
#### Slurp old and new files
###{
### local $/ ; # locally set record operator to undefined, ie. enable whole-file mode
### $old=<OLD>;
### $new=<NEW>;
###}
# reset time
exetime(1);
### if ( $debug ) {
### open(RAWDIFF,">","latexdiff.debug.oldfile");
### print RAWDIFF $old;
### close(RAWDIFF);
### open(RAWDIFF,">","latexdiff.debug.newfile");
### print RAWDIFF $new;
### close(RAWDIFF);
### }
### print STDERR "DEBUG: before splitting old ",length($old),"\n" if $debug;
($oldpreamble,$oldbody,$oldpost)=splitdoc($old,'\\\\begin\{document\}','\\\\end\{document\}');
###if ( $oldpreamble =~ m/\\usepackage\[(\w*?)\]\{inputenc\}/ ) {
### $encoding=$1;
### require Encode;
### print STDERR "Detected input encoding $encoding.\n" if $verbose;
### $oldpreamble=Encode::decode($encoding,$oldpreamble);
### $oldbody=Encode::decode($encoding,$oldbody);
### $oldpost=Encode::decode($encoding,$oldpost);
#### Encode::from_to($oldpreamble,$encoding,"utf8");
#### Encode::from_to($oldbody,$encoding,"utf8");
#### Encode::from_to($oldpost,$encoding,"utf8");
### }
###print STDERR "DEBUG: before splitting new ",length($old),"\n" if $debug;
($newpreamble,$newbody,$newpost)=splitdoc($new,'\\\\begin\{document\}','\\\\end\{document\}');
###if ( $newpreamble =~ m/\\usepackage\[(\w*?)\]\{inputenc\}/ ) {
### if ($encoding ne $1 ) {
### die "Input encoding in both old and new file must be the same.\n";
### }
### $newpreamble=Encode::decode($encoding,$newpreamble);
### $newbody=Encode::decode($encoding,$newbody);
### $newpost=Encode::decode($encoding,$newpost);
### # Encode::from_to($newpreamble,$encoding,"utf8");
### # Encode::from_to($newbody,$encoding,"utf8");
### # Encode::from_to($newpost,$encoding,"utf8");
###}
if ($flatten) {
$oldbody=flatten($oldbody,$oldpreamble,File::Spec->rel2abs($oldfile),$encoding);
$newbody=flatten($newbody,$newpreamble,File::Spec->rel2abs($newfile),$encoding);
# flatten preamble
$oldpreamble=flatten($oldpreamble,$oldpreamble,File::Spec->rel2abs($oldfile),$encoding);
$newpreamble=flatten($newpreamble,$newpreamble,File::Spec->rel2abs($newfile),$encoding);
### if ( $debug ) {
### open(FILE,">","latexdiff.debug.flatold");
### print FILE $oldpreamble,'\\begin{document}',$oldbody,'\\end{document}',$oldpost;
### close(FILE);