Debian Codegraph @

texk/texlive/linked_scripts/latexdiff/latexdiff.pl

raw
1 #!/usr/bin/env perl
2 ##!/usr/bin/perl -w
3 # latexdiff - differences two latex files on the word level
4 # and produces a latex file with the differences marked up.
5 #
6 # Copyright (C) 2004-22 F J Tilmann ([email protected])
7 #
8 # Repository/issue tracker: https://github.com/ftilmann/latexdiff
9 # CTAN page: http://www.ctan.org/pkg/latexdiff
10 #
11 # This program is free software: you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation, either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #
23 # Detailed usage information at the end of the file
24 #
25 #
26 # Note references to issue numbers are for the github repository of latexdiff: https://github.com/ftilmann/latexdiff
27 #
28 # Version 1.4.0:
29 #
30 # New features:
31 # - add directive pairs %BEGIN DIF(ADD|DEL), %END DIF(ADD|DEL) that causes blocks to be marked up as a whole
32 # - add directive pair %BEGIN DIFNOMARKUP, %END DIFNOMARKUP that can suppress markup locally
33 # - add option for letter-level markup for single substituted words, controlled by configuration variable MAXCHANGESLETTER, which limits this behaviour to a small number of changes. By default this is set to 1 - other sensible settings are 0 and 2.
34 #
35 # Bug fixes:
36 # - Fix a bug in pre-/postprocessing that led to odd behaviour if some characters with special meaning, like _,^ were used in particular contexts in verbatim environments. Fixes #305
37 # - Fix a bug in the preprocessing that detects \[ \] as math expression (it was interpreting \\] as \+ \] instead of correctly \\ + ]
38 # - Commands that were both in the safecmd and textcmd list, and which have additional arguments beyond the last textual one (optional or non-optional) could lead to errors, if there was a change in those earlier arguments (fixes #306, first reported through debian bug report)
39 # - super- and subscripts without enclosing curly braces were assumed to be a simple expression, while in reality they could be commands with complicated (nested) arguments. These cases are not processed correctly. Fixes #279
40 # - in show-textcmd and show-safecmd some extra regex characters are now properly removed
41 # - special preamble additions for highlighting graphics or lines in verbatim text no longer overwrite the definitions in a user-included
42 # preamble file (via --preamble option). If the user-included preamble file does not define important commands, then they continue to be added (some simple
43 # heuristics are used to decide whether to add or not are used, so this decision might not be perfect). Fixes #310 .
44 # - nested array blocks now no longer lead to errors, even when nothing is changed in them (fixes #287).
45 # - sometimes, \protect commands would become separated from the commands they are supposed to apply, too. They are now kept together in the same token. Fixes #284
46 # - Improper definition of the DIFverbatim environment led to warnings. This has been corrected now. Fixes #320.
47 # - In --flatten mode, input commands in verbatim environments were erroneously expanded. This is now suppressed. Fixes #321
48 # - \i is now a safe command
49 # - \frac ab is now processed correctly (Fixes #322)
50 #
51 # Modified behaviour:
52 # - Commands/RegExs explicitly defined as not safe with --exclude-safecmd are now also considered unsafe in COARSE and WHOLE math markup (Fixes #311)
53 # - --no-del now also removes deleted comments
54 # - --show-... commands now have different behaviour dependent on whether old.tex and new.tex are specified. If they are not not then the initial setup is shown. If they are specified, then the full configuration is shown, which includes some additions of internal commands, and modifications based on what packages are present on the system, or are used in the .tex files. Either way, no differencing takes place.
55 #
56 #
57 #
58 # Version 1.3.4:
59 # New features:
60 # - Option to use lua-ul instead of ulem (for use with LuaLaTeX) (fixes #17, #60, #188, #255, #270)
61 #
62 # Enhancements:
63 # - If amsmath is detected as one of the included packages then modify the sout command to wrap with \text in math mode, such that deleted text is actually struck out in equations; the standard behaviour is to underline instead of strike-out due to the limitations in the ulem package (based on the idea described in PR #263)
64 #
65 # Bug fix
66 # - sometimes the introduction of aux commands to show deleted lists or descriptions leaves in place empty auxiliary
67 # list environments, which would cause error messages (though skipping messages would result in a correct output pdf).
68 # These are now removed.
69 # - add more mboxsafecmd and safecmd commands for SIunitx to stay compatible with newer versionsof SIunitx (PR #283, fixing issue #282, including reopened #282, contributed by github user joe6302413)
70 # - File added via --preamble option is no longer assumed to be ASCII, but read either with encoding as defined by --encoding option or using the encoding of the LOCALE (fixes issue #285 )
71 # - multicolumn argument is now treated as text
72 # - when tikz-dependency package is used, \& is no longer a safe command as it has special meaning inside dependency environment. The fix is a bit of a hack as really it should only be considered unsafe within dependency environment (fixes (mostly) issue #303 )
73 # - the listings package has trouble with non-ASCII chars. The encoding is now set (thanks to github user anka-213 for finding this). Fixes #304
74 #
75 # Refactor:
76 # - Use perltidy for uniform formatting, and removing tab indents
77 #
78 # Version 1.3.3:
79 # New features:
80 # - Option --no-del to remove all deleted text (merge contributed by github user tdegeus PR #252, fixing issue #66
81 #
82 # Bug fixes:
83 # - Abbreviations involving punctuations within them. They need special treatment because otherwise in some
84 # circumstances the gnoring of white space differences in conjunction with merging according to MINWORDSBLOCK rule
85 # could turn 'i.e.' into 'i.\PAR e.' (see https://github.com/ftilmann/latexdiff/issues/269). A few abbreviations
86 # are now hard-coded and treated as atomic:
87 # English: i.e., e.g. Deutsch: z.B.
88 # (fixes issue #269)
89 # - In WHOLE and COARSE math modes, now properly treat math environments with arguments such as \alignat. Fixes #251
90 # - For FINE math mode, multiple improvments to the processing work flow yield more robust outcomes. In particular, changes
91 # to the equation type, e.g. \begin{displaymath} -> \begin{equation} without modifications now usually no longer result
92 # in errors. (Partially) fixes issues #235 and #244.
93 # - When encountering deleted math array environments such as align or eqnarray, rather than replacing them with a
94 # fixed replacement environment (e.g. align* or eqnarray*), an asterisk is now added to the original command, which
95 # in amsmath (and with eqnarray) will result in the same environment but without line numbers. Config variable MATHARRREPL
96 # is therefore (nearly) redundant, and a depracation warning is given when it is set. Reference to MATHARRREPL are have
97 # been removed from the manual (there is one exception, when it's still being used: sometimes latexdiff can figure out
98 # that there is a deleted array environment, but does not know which one. In this case, MATHARRREPL is still being used
99 # to encapsulate these parts of the source, and therefore it is still set internally. But this is a quite rare situation).
100 # Fixes issue #216
101 # - Unlike 'array' environment, 'split' (amsmath) does not work in argument of \DIFadd or \DIFdl in UNDERLINE modes; therefore remove it from ARRENV configuration variable.
102 # Exclude \begin and \end in math environments in COARSE and WHOLE modes. Fixes #258. Fixes #109
103 # - --flatten now works for empty files. Fixes issue #242
104 # - improved processing of Chinese and Japanese texts in that splitting is done based on characters. Thanks to LuXu (Oliver Lew) in git for working this out. Fixes #229, fixes #145
105
106 # Version 1.3.2
107 # API adaptions:
108 # - latexdiff now completes with exit code 0 after --help or --version command (see issue #248)
109 # New features / feature extensions
110 # - extend CUSTOMDIFCMD related postprocessing to deal properly with multiline commands, or a sequence of several commands in the same line (see github issue #204)
111 # - Support for additional macros from import package (\import, \inputfrom, \includefrom, \subimport,\subinputfrom, \subincludefrom). Provided by janniklasrose in PR #243 (fixes #239)
112 # - replace default driver dvips->pdftex
113 # Bug fixes:
114 # - fix issue #206 affecting proper markup of text commands which are not also safe cmd's and have multiple arguments
115 # - fix issue #210 by adding \eqref (amsmath package) to the list of safe commands
116 # - fix bug reported in issue #168 mangled verbatim line environment
117 # - fix bug reported in issue #218 by replacing \hspace{0pt} after \mbox{..} auxiliary commands with \hskip0pt.
118 # - more ways to process \frac correctly with atomic arguments (committed by julianuu PR #246
119 # - 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)
120 # - -h string fix: add -driver option
121 #
122 # Version 1.3.1.1
123 # - remove spurious \n to fix error: Unknown regexp modifier "/n" at .../latexdiff line 1974, near "=~ " (see github issue #201)
124 #
125 # Version 1.3.1
126 # Bug fixes:
127 # - remove some uninitialised variable $2 warnings in string substitution in flatten function in case included file is not found
128 # - add minimal postprocessing to diff processing of preamble commands (replace \RIGHTBRACE by \} )
129 # - pre-processing: replace (contributed) routine take_comments_and_enter_from_frac() with take_comments_and_newline_from_frac(), which does the same thing
130 # (remove whitespace characters and comments between the argument of \frac commands) in an easier and more robust way. In addition, it
131 # will replace commands like \frac12 with \frac{1}{2} as pre-processing step. Fixes issue #184
132 # - add "intertext" to list of unsafe math commands @UNSAFEMATHCMD . Fixes issue #179
133 # - provide citation command patterns for biblatex and protect them with mbox'es. Fixes issue #199
134 # - 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
135 # is needed because some bibliography styles add such in-command-sequence spaces) Fixes issues: #178 #198
136 # - 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)
137 # (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
138 # \bibitem is hardwired to be the only member of this class (fixes issue #194, #174)
139 # Features:
140 # - add some special processing for revtex bibliography commands, so that the spaces between bibliography commands \bibfield and \bibinfo and their arguments are ignored.
141 # (fixes issue #194, should fix #174)
142 #
143 # Version 1.3.0 (7 October 2018):
144 # - treat options to \documentclass as potential package names (some packages allow implicit loading of or imply selected packages
145 # - improved pattern matching: now allows nested angular brackets, and is no longer confused by escaped curly braces
146 # - 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 .
147 # - 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)
148 # (see new configuration variable VERBATIMLINEENV) (several issues and pull requests by jprotze)
149 # - --flatten: now supports \verbatiminput and \lstlistinput
150 # - --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)
151 # - added to textcmds: \intertext
152 # - new config variable CUSTOMDIFCMD to allow defining special versions of commands in added or deleted blocks (Pull request by github user jprotze)
153 # - added option -no-links (mostly for use by latexdiff-vc in only-changes modes) (Pull request by github user jprotze)
154 # - new option --filter-script to run both input through a pre-processing script (PR jasonmccsmith #167)
155 # new option --no-filter-stderr to hide stderr output from filter-script (potentially dangerous, as this might hide malfunctioning of filter scripts)
156 # - --flatten now can deal with imports made using the import package {PR jasonmccsmith #173)
157 # Bug fixes:
158 # - pattern matching of \verb and \lstinline commands had an error which meant they would trigger on commands beginning with \verb.
159 # - In description environments, mark up item descriptions by effectively reating the insides of item commannds as text commands (fixes #161)
160 #
161 #
162 # Version 1.2.1 (22 June 2017)
163 # - add "DeclareOldFontCommand" to styles using \bf or \sf old style font commands (fixies issue #92 )
164 # - improved markup: process lstinline commands in listings package correctly
165 # for styles using colour, \verb and \lstinline arguments are marked up with colour (blue for added, red for deleted)
166 # - 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)
167 # - bug fix: when deleted \item commands are followed immediately by unsafe commands, they were not restored properly
168 # (thanks to J. Protze for pull request) (pull request #89)
169 # - treat lstlisting and comment as equivalent to verbatim environment
170 # make environments that are treated like verbatim environments configurable (config variable VERBATIMENV)
171 # treat lstinlne as equivalent to verb command
172 # partially addresses issue #38
173 # - refactoring: set default configuration variables in a hash, and those that correspond to lists
174 # - feature: option --add-to-config used to amend configuration variables, which are regex pattern lists
175 # - bug fix: deleted figures when endfloat package is activated
176 # - bug fix: alignat environment now always processed correctly (fix issues #65)
177 # - bug fix: avoid processing of commands as potential files in routine init_regex_arr (fix issue #70 )
178 # - minimal feature enhancement: treat '@' as allowed character in commands (strictly speaking requires prior \makeatletter statement, but always assuming it to be
179 # @ 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)
180 # - 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)
181 # - bug fix: flatten would incorrectly attempt to process commented out \include commands (from discussion in issue #77 )
182 # - 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)
183 #
184 # Version 1.2.0:
185 # - highlight new and deleted figures
186 # - bug fix in title mark-up. Previously deleted commands in title (such as \title, \author or \date) were marked up erroneously
187 # - (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
188 # - depracation fix: left brace in RegEx now needs to be escaped
189 # - add type PDFCOMMENT based on issue #49 submitted by github user peci1 (Martin Pecka)
190 # - make utf8 the default encoding
191 #
192 # Version 1.1.1
193 # - patch mhchem: allow ce in equations
194 # - flatten now also expands \input etc. in the preamble (but not \usepackage!)
195 # - Better support for Japanese ( contributed by github user kshramt )
196 # - prevent duplicated verbatim hashes (patch contributed by github user therussianjig, issue #36)
197 # - disable deleted label commands (fixes issue #31)
198 # - introduce post-processing to reinstate most deleted environments and all needed item commands (fixes issue #1)
199 #
200 # Version 1.1.0
201 # - treat diacritics (\",\', etc) as safe commands
202 # - treat \_ and \& correctly as safe commands, even if used without spacing to the next word
203 # - Add a BOLD markup type that sets added text in bold face (Contribution by Victor Zabalza via pull request )
204 # - 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)
205 # - 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)
206 # - 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)
207 # - 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)
208 # - new subtype ONLYCHANGEDPAGE outputs only changed pages (might not work well for floating material)
209 # - new subtype ZLABEL operates similarly to LABEL but uses absolute page numbers (needs zref package)
210 # - undocumented option --debug/--nodebug to override default setting for debug mode (Default: 0 for release version, 1: for development version
211 #
212 # Version 1.0.4
213 # - 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)
214 # - new subtype LABEL which gives each change a label. This can later be used to only display pages where changes
215 # 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
216 # - Configuration variables take into accout some commands from additional packages:
217 # tikzpicture environment now treated as PICTUREENV, and \smallmatrix in ARRENV (amsmath)
218 # - --flatten: support for \subfile command (subfiles package) (in response to http://tex.stackexchange.com/questions/167620/latexdiff-with-subfiles )
219 # - --flatten: \bibliography commands expand if corresponding bbl file present
220 # - angled bracket optional commands now parsed correctly (patch #3570) submitted by Dave Kleinschmidt (thanks)
221 # - \RequirePackage now treated as synonym of \usepackage with respect to setting packages
222 # - special rules for apacite package (redefine citation commands)
223 # - recognise /dev/null as 'file-like' arguments for --preamble and --config options
224 # - fix units package incompatibility with ulem for text maths statements $ ..$ (thanks to Stuart Prescott for reporting this)
225 # - amsmath environment cases treated correctly (Bug fix #19029) (thanks to Jalar)
226 # - {,} in comments no longer confuse latexdiff (Bug fix #19146)
227 # - \% in one-letter sub/Superscripts was not converted correctly
228 #
229 # Version 1.0.3
230 # - fix bug in add_safe_commands that made latexdiff hang on DeclareMathOperator
231 # command in preamble
232 # - \(..\) inline math expressions were not parsed correctly, if they contained a linebreak
233 # - applied patch contributed by tomflannaghan via Berlios: [ Patch #3431 ] Adds correct handling of \left< and \right>
234 # - \$ is treated correctly as a literal dollar sign (thanks to Reed Cartwright and Joshua Miller for reporting this bug
235 # and sketching out the solution)
236 # - \^ and \_ are correctly interpreted as accent and underlined space, respectively, not as superscript of subscript
237 # (thanks to Wail Yahyaoui for pointing out this bug)
238 #
239 # Version 1.0.1 - treat \big,\bigg etc. equivalently to \left and
240 # \right - include starred version in MATHENV - apply
241 # - flatten recursively and --flatten expansion is now
242 # aware of comments (thanks to Tim Connors for patch)
243 # - Change to post-processing for more reliability for
244 # deleted math environments
245 # - On linux systems, recognise and remove DOS style newlines
246 # - Provide markup for some special preamble commands (\title,
247 # \author,\date,
248 # - configurable by setting context2cmd
249 # - for styles using ulem package, remove \emph and \text.. from list of
250 # safe commands in order to allow linebreaks within the
251 # highlighted sections.
252 # - for ulem style, now show citations by enclosing them in \mbox commands.
253 # This unfortunately implies linebreaks within citations no longer function,
254 # so this functionality can be turned off (Option --disable-citation-markup).
255 # With --enable-citation-markup, the mbox markup is forced for other styles)
256 # - new substyle COLOR. This is particularly useful for marking up citations
257 # and some special post-processing is implemented to retain cite
258 # commands in deleted blocks.
259 # - four different levels of math-markup
260 # - Option --driver for choosing driver for modes employing changebar package
261 # - accept \\* as valid command (and other commands of form \.*). Also accept
262 # \<nl> (backslashed newline)
263 # - some typo fixes, include commands defined in preamble as safe commands
264 # (Sebastian Gouezel)
265 # - include compared filenames as comments as line 2 and 3 of
266 # the preamble (can be modified with option --label, and suppressed with
267 # --no-label), option --visible-label to show files in generated pdf or dvi
268 # at the beginning of main document
269 #
270 # Version 0.5 A number of minor improvements based on feedback
271 # Deleted blocks are now shown before added blocks
272 # Package specific processing
273 #
274 # Version 0.43 unreleased typo in list of styles at the end
275 # Add protect to all \cbstart, \cbend commands
276 # More robust substitution of deleted math commands
277 #
278 # Version 0.42 November 06 Bug fixes only
279 #
280 # Version 0.4 March 06 option for fast differencing using UNIX diff command, several minor bug fixes (\par bug, improved highlighting of textcmds)
281 #
282 # Version 0.3 August 05 improved parsing of displayed math, --allow-spaces
283 # option, several minor bug fixes
284 #
285 # Version 0.25 October 04 Fix bug with deleted equations, add math mode commands to safecmd, add | to allowed interpunctuation signs
286 # Version 0.2 September 04 extension to utf-8 and variable encodings
287 # Version 0.1 August 04 First public release
288
289 # Inserted block for stand-alone version replaces
290 # use Algorithm::Diff qw(traverse_sequences);
291 # in standard version
292 # The following BEGIN block contains a verbatim copy of
293 # Ned Konz' Algorithm::Diff package version 1.15 except
294 # that all POD documentation has been stripped out.
295 # I encourage you to download and install the Algorithm::Diff
296 # package and use the standard latexdiff version instead
297 # (current distribution available from http://search.cpan.org/~nedkonz/Algorithm-Diff-1.15
298 # the most recent version can be found via http://search.cpan.org/search?module=Algorithm::Diff )
299 # Please note the LICENCE for Algorithm::Diff :
300 # "Copyright (c) 2000-2002 Ned Konz. All rights reserved.
301 # This program is free software;
302 # you can redistribute it and/or modify it under the same terms
303 # as Perl itself."
304 # The stand-alone version of latexdiff is provided as a convenience
305 # for latex users with no knowledge of PERL who do not wish to install
306 # additional packages to be able to use latexdiff. If you believe
307 # the inlining of Algorithm::Diff violates its license please contact
308 # me and I will modify the latexdiff distribution accordingly.
309 # Frederik Tilmann ([email protected])
310 BEGIN {
311 package Algorithm::Diff;
312 use strict;
313 use vars qw($VERSION @EXPORT_OK @ISA @EXPORT);
314 use integer; # see below in _replaceNextLargerWith() for mod to make
315 # if you don't use this
316 require Exporter;
317 @ISA = qw(Exporter);
318 @EXPORT = qw();
319 @EXPORT_OK = qw(LCS diff traverse_sequences traverse_balanced sdiff);
320 $VERSION = sprintf('%d.%02d so', (q$Revision: 1.15 $ =~ /\d+/g));
321
322 # McIlroy-Hunt diff algorithm
323 # Adapted from the Smalltalk code of Mario I. Wolczko, <[email protected]>
324 # by Ned Konz, [email protected]
325
326
327 # Create a hash that maps each element of $aCollection to the set of positions
328 # it occupies in $aCollection, restricted to the elements within the range of
329 # indexes specified by $start and $end.
330 # The fourth parameter is a subroutine reference that will be called to
331 # generate a string to use as a key.
332 # Additional parameters, if any, will be passed to this subroutine.
333 #
334 # my $hashRef = _withPositionsOfInInterval( \@array, $start, $end, $keyGen );
335
336 sub _withPositionsOfInInterval
337 {
338 my $aCollection = shift; # array ref
339 my $start = shift;
340 my $end = shift;
341 my $keyGen = shift;
342 my %d;
343 my $index;
344 for ( $index = $start ; $index <= $end ; $index++ )
345 {
346 my $element = $aCollection->[$index];
347 my $key = &$keyGen( $element, @_ );
348 if ( exists( $d{$key} ) )
349 {
350 unshift ( @{ $d{$key} }, $index );
351 }
352 else
353 {
354 $d{$key} = [$index];
355 }
356 }
357 return wantarray ? %d : \%d;
358 }
359
360 # Find the place at which aValue would normally be inserted into the array. If
361 # that place is already occupied by aValue, do nothing, and return undef. If
362 # the place does not exist (i.e., it is off the end of the array), add it to
363 # the end, otherwise replace the element at that point with aValue.
364 # It is assumed that the array's values are numeric.
365 # This is where the bulk (75%) of the time is spent in this module, so try to
366 # make it fast!
367
368 sub _replaceNextLargerWith
369 {
370 my ( $array, $aValue, $high ) = @_;
371 $high ||= $#$array;
372
373 # off the end?
374 if ( $high == -1 || $aValue > $array->[-1] )
375 {
376 push ( @$array, $aValue );
377 return $high + 1;
378 }
379
380 # binary search for insertion point...
381 my $low = 0;
382 my $index;
383 my $found;
384 while ( $low <= $high )
385 {
386 $index = ( $high + $low ) / 2;
387
388 # $index = int(( $high + $low ) / 2); # without 'use integer'
389 $found = $array->[$index];
390
391 if ( $aValue == $found )
392 {
393 return undef;
394 }
395 elsif ( $aValue > $found )
396 {
397 $low = $index + 1;
398 }
399 else
400 {
401 $high = $index - 1;
402 }
403 }
404
405 # now insertion point is in $low.
406 $array->[$low] = $aValue; # overwrite next larger
407 return $low;
408 }
409
410 # This method computes the longest common subsequence in $a and $b.
411
412 # Result is array or ref, whose contents is such that
413 # $a->[ $i ] == $b->[ $result[ $i ] ]
414 # foreach $i in ( 0 .. $#result ) if $result[ $i ] is defined.
415
416 # An additional argument may be passed; this is a hash or key generating
417 # function that should return a string that uniquely identifies the given
418 # element. It should be the case that if the key is the same, the elements
419 # will compare the same. If this parameter is undef or missing, the key
420 # will be the element as a string.
421
422 # By default, comparisons will use "eq" and elements will be turned into keys
423 # using the default stringizing operator '""'.
424
425 # Additional parameters, if any, will be passed to the key generation routine.
426
427 sub _longestCommonSubsequence
428 {
429 my $a = shift; # array ref
430 my $b = shift; # array ref
431 my $keyGen = shift; # code ref
432 my $compare; # code ref
433
434 # set up code refs
435 # Note that these are optimized.
436 if ( !defined($keyGen) ) # optimize for strings
437 {
438 $keyGen = sub { $_[0] };
439 $compare = sub { my ( $a, $b ) = @_; $a eq $b };
440 }
441 else
442 {
443 $compare = sub {
444 my $a = shift;
445 my $b = shift;
446 &$keyGen( $a, @_ ) eq &$keyGen( $b, @_ );
447 };
448 }
449
450 my ( $aStart, $aFinish, $bStart, $bFinish, $matchVector ) =
451 ( 0, $#$a, 0, $#$b, [] );
452
453 # First we prune off any common elements at the beginning
454 while ( $aStart <= $aFinish
455 and $bStart <= $bFinish
456 and &$compare( $a->[$aStart], $b->[$bStart], @_ ) )
457 {
458 $matchVector->[ $aStart++ ] = $bStart++;
459 }
460
461 # now the end
462 while ( $aStart <= $aFinish
463 and $bStart <= $bFinish
464 and &$compare( $a->[$aFinish], $b->[$bFinish], @_ ) )
465 {
466 $matchVector->[ $aFinish-- ] = $bFinish--;
467 }
468
469 # Now compute the equivalence classes of positions of elements
470 my $bMatches =
471 _withPositionsOfInInterval( $b, $bStart, $bFinish, $keyGen, @_ );
472 my $thresh = [];
473 my $links = [];
474
475 my ( $i, $ai, $j, $k );
476 for ( $i = $aStart ; $i <= $aFinish ; $i++ )
477 {
478 $ai = &$keyGen( $a->[$i], @_ );
479 if ( exists( $bMatches->{$ai} ) )
480 {
481 $k = 0;
482 for $j ( @{ $bMatches->{$ai} } )
483 {
484
485 # optimization: most of the time this will be true
486 if ( $k and $thresh->[$k] > $j and $thresh->[ $k - 1 ] < $j )
487 {
488 $thresh->[$k] = $j;
489 }
490 else
491 {
492 $k = _replaceNextLargerWith( $thresh, $j, $k );
493 }
494
495 # oddly, it's faster to always test this (CPU cache?).
496 if ( defined($k) )
497 {
498 $links->[$k] =
499 [ ( $k ? $links->[ $k - 1 ] : undef ), $i, $j ];
500 }
501 }
502 }
503 }
504
505 if (@$thresh)
506 {
507 for ( my $link = $links->[$#$thresh] ; $link ; $link = $link->[0] )
508 {
509 $matchVector->[ $link->[1] ] = $link->[2];
510 }
511 }
512
513 return wantarray ? @$matchVector : $matchVector;
514 }
515
516 sub traverse_sequences
517 {
518 my $a = shift; # array ref
519 my $b = shift; # array ref
520 my $callbacks = shift || {};
521 my $keyGen = shift;
522 my $matchCallback = $callbacks->{'MATCH'} || sub { };
523 my $discardACallback = $callbacks->{'DISCARD_A'} || sub { };
524 my $finishedACallback = $callbacks->{'A_FINISHED'};
525 my $discardBCallback = $callbacks->{'DISCARD_B'} || sub { };
526 my $finishedBCallback = $callbacks->{'B_FINISHED'};
527 my $matchVector = _longestCommonSubsequence( $a, $b, $keyGen, @_ );
528
529 # Process all the lines in @$matchVector
530 my $lastA = $#$a;
531 my $lastB = $#$b;
532 my $bi = 0;
533 my $ai;
534
535 for ( $ai = 0 ; $ai <= $#$matchVector ; $ai++ )
536 {
537 my $bLine = $matchVector->[$ai];
538 if ( defined($bLine) ) # matched
539 {
540 &$discardBCallback( $ai, $bi++, @_ ) while $bi < $bLine;
541 &$matchCallback( $ai, $bi++, @_ );
542 }
543 else
544 {
545 &$discardACallback( $ai, $bi, @_ );
546 }
547 }
548
549 # The last entry (if any) processed was a match.
550 # $ai and $bi point just past the last matching lines in their sequences.
551
552 while ( $ai <= $lastA or $bi <= $lastB )
553 {
554
555 # last A?
556 if ( $ai == $lastA + 1 and $bi <= $lastB )
557 {
558 if ( defined($finishedACallback) )
559 {
560 &$finishedACallback( $lastA, @_ );
561 $finishedACallback = undef;
562 }
563 else
564 {
565 &$discardBCallback( $ai, $bi++, @_ ) while $bi <= $lastB;
566 }
567 }
568
569 # last B?
570 if ( $bi == $lastB + 1 and $ai <= $lastA )
571 {
572 if ( defined($finishedBCallback) )
573 {
574 &$finishedBCallback( $lastB, @_ );
575 $finishedBCallback = undef;
576 }
577 else
578 {
579 &$discardACallback( $ai++, $bi, @_ ) while $ai <= $lastA;
580 }
581 }
582
583 &$discardACallback( $ai++, $bi, @_ ) if $ai <= $lastA;
584 &$discardBCallback( $ai, $bi++, @_ ) if $bi <= $lastB;
585 }
586
587 return 1;
588 }
589
590 sub traverse_balanced
591 {
592 my $a = shift; # array ref
593 my $b = shift; # array ref
594 my $callbacks = shift || {};
595 my $keyGen = shift;
596 my $matchCallback = $callbacks->{'MATCH'} || sub { };
597 my $discardACallback = $callbacks->{'DISCARD_A'} || sub { };
598 my $discardBCallback = $callbacks->{'DISCARD_B'} || sub { };
599 my $changeCallback = $callbacks->{'CHANGE'};
600 my $matchVector = _longestCommonSubsequence( $a, $b, $keyGen, @_ );
601
602 # Process all the lines in match vector
603 my $lastA = $#$a;
604 my $lastB = $#$b;
605 my $bi = 0;
606 my $ai = 0;
607 my $ma = -1;
608 my $mb;
609
610 while (1)
611 {
612
613 # Find next match indices $ma and $mb
614 do { $ma++ } while ( $ma <= $#$matchVector && !defined $matchVector->[$ma] );
615
616 last if $ma > $#$matchVector; # end of matchVector?
617 $mb = $matchVector->[$ma];
618
619 # Proceed with discard a/b or change events until
620 # next match
621 while ( $ai < $ma || $bi < $mb )
622 {
623
624 if ( $ai < $ma && $bi < $mb )
625 {
626
627 # Change
628 if ( defined $changeCallback )
629 {
630 &$changeCallback( $ai++, $bi++, @_ );
631 }
632 else
633 {
634 &$discardACallback( $ai++, $bi, @_ );
635 &$discardBCallback( $ai, $bi++, @_ );
636 }
637 }
638 elsif ( $ai < $ma )
639 {
640 &$discardACallback( $ai++, $bi, @_ );
641 }
642 else
643 {
644
645 # $bi < $mb
646 &$discardBCallback( $ai, $bi++, @_ );
647 }
648 }
649
650 # Match
651 &$matchCallback( $ai++, $bi++, @_ );
652 }
653
654 while ( $ai <= $lastA || $bi <= $lastB )
655 {
656 if ( $ai <= $lastA && $bi <= $lastB )
657 {
658
659 # Change
660 if ( defined $changeCallback )
661 {
662 &$changeCallback( $ai++, $bi++, @_ );
663 }
664 else
665 {
666 &$discardACallback( $ai++, $bi, @_ );
667 &$discardBCallback( $ai, $bi++, @_ );
668 }
669 }
670 elsif ( $ai <= $lastA )
671 {
672 &$discardACallback( $ai++, $bi, @_ );
673 }
674 else
675 {
676
677 # $bi <= $lastB
678 &$discardBCallback( $ai, $bi++, @_ );
679 }
680 }
681
682 return 1;
683 }
684
685 sub LCS
686 {
687 my $a = shift; # array ref
688 my $matchVector = _longestCommonSubsequence( $a, @_ );
689 my @retval;
690 my $i;
691 for ( $i = 0 ; $i <= $#$matchVector ; $i++ )
692 {
693 if ( defined( $matchVector->[$i] ) )
694 {
695 push ( @retval, $a->[$i] );
696 }
697 }
698 return wantarray ? @retval : \@retval;
699 }
700
701 sub diff
702 {
703 my $a = shift; # array ref
704 my $b = shift; # array ref
705 my $retval = [];
706 my $hunk = [];
707 my $discard = sub { push ( @$hunk, [ '-', $_[0], $a->[ $_[0] ] ] ) };
708 my $add = sub { push ( @$hunk, [ '+', $_[1], $b->[ $_[1] ] ] ) };
709 my $match = sub { push ( @$retval, $hunk ) if scalar(@$hunk); $hunk = [] };
710 traverse_sequences( $a, $b,
711 { MATCH => $match, DISCARD_A => $discard, DISCARD_B => $add }, @_ );
712 &$match();
713 return wantarray ? @$retval : $retval;
714 }
715
716 sub sdiff
717 {
718 my $a = shift; # array ref
719 my $b = shift; # array ref
720 my $retval = [];
721 my $discard = sub { push ( @$retval, [ '-', $a->[ $_[0] ], "" ] ) };
722 my $add = sub { push ( @$retval, [ '+', "", $b->[ $_[1] ] ] ) };
723 my $change = sub {
724 push ( @$retval, [ 'c', $a->[ $_[0] ], $b->[ $_[1] ] ] );
725 };
726 my $match = sub {
727 push ( @$retval, [ 'u', $a->[ $_[0] ], $b->[ $_[1] ] ] );
728 };
729 traverse_balanced(
730 $a,
731 $b,
732 {
733 MATCH => $match,
734 DISCARD_A => $discard,
735 DISCARD_B => $add,
736 CHANGE => $change,
737 },
738 @_
739 );
740 return wantarray ? @$retval : $retval;
741 }
742
743 1;
744 }
745 import Algorithm::Diff qw(traverse_sequences);
746 # End of inserted block for stand-alone version
747
748 use Getopt::Long;
749 use strict;
750 use warnings;
751 use utf8;
752
753 use File::Spec;
754
755 my ($algodiffversion) = split( / /, $Algorithm::Diff::VERSION );
756
757 my ($versionstring) = <<EOF ;
758 This is LATEXDIFF 1.4.0 (Algorithm::Diff $Algorithm::Diff::VERSION, Perl $^V)
759 (c) 2004-2024 F J Tilmann
760 EOF
761
762 # Hash with defaults for configuration variables. These marked undef have default values constructed from list defined in the DATA block
763 # (under tag CONFIG)
764 my %CONFIG = (
765 MINWORDSBLOCK => 3, # minimum number of tokens to form an independent block
766 # shorter identical blocks will be merged to the previous word
767 MAXCHANGESLETTER => 1, # maximum number of changes in a letter for letter-level markup
768 # (rather than standard word level) to be used
769 SCALEDELGRAPHICS => 0.5, # factor with which deleted figures will be scaled down (i.e. 0.5 implies they are shown at half linear size)
770 # this is only used for --dgraphics-markup=BOTH option
771 FLOATENV => undef, # Environments in which FL variants of defined commands are used
772 PICTUREENV => undef, # Environments in which all change markup is removed
773 MATHENV => undef, # Environments turning on display math mode (code also knows about \[ and \])
774 MATHREPL => 'displaymath', # Environment introducing deleted maths blocks
775 MATHARRENV => undef, # Environments turning on eqnarray math mode
776 MATHARRREPL => 'eqnarray*', # Environment introducing deleted maths blocks (note that now the starred varieties are being used, so this is only used to replace MATHMODE environments (where original environment is unknown)
777 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
778 COUNTERCMD => undef, # COUNTERCMD textcmds which are associated with a counter
779 # If any of these commands occur in a deleted block
780 # they will be followed by an \addtocounter{...}{-1}
781 # for the associated counter such that the overall numbers
782 # should be the same as in the new file
783 LISTENV => undef, # list making environments - they will generally be kept
784 VERBATIMENV => undef, # Environments whose content should be treated as verbatim text and not be touched
785 VERBATIMLINEENV => undef, # Environments whose content should be treated as verbatim text and processed in line diff mode
786 CUSTOMDIFCMD => undef, # Custom dif command. Is defined in the document as a \DELcommand and \ADDcommand version to be replaced by the diff
787 ITEMCMD => 'item' # command marking item in a list environment
788 );
789 # Configuration variables: these have to be visible from the subroutines
790 my (
791 $ARRENV, $COUNTERCMD, $FLOATENV, $ITEMCMD, $LISTENV, $MATHARRENV,
792 $MATHARRREPL, $MATHENV, $MATHREPL, $MAXCHANGESLETTER, $MINWORDSBLOCK, $PICTUREENV,
793 $SCALEDELGRAPHICS, $VERBATIMENV, $VERBATIMLINEENV, $CUSTOMDIFCMD,
794 );
795
796 # my $MINWORDSBLOCK=3; # minimum number of tokens to form an independent block
797 # # shorter identical blocks will be merged to the previous word
798 # 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)
799 # # this is only used for --graphics-markup=BOTH option
800 # my $FLOATENV='(?:figure|table|plate)[\w\d*@]*' ; # Environments in which FL variants of defined commands are used
801 # my $PICTUREENV='(?:picture|tikzpicture|DIFnomarkup)[\w\d*@]*' ; # Environments in which all change markup is removed
802 # my $MATHENV='(?:equation[*]?|displaymath|DOLLARDOLLAR)[*]?' ; # Environments turning on display math mode (code also knows about \[ and \])
803 # my $MATHREPL='displaymath'; # Environment introducing deleted maths blocks
804 # my $MATHARRENV='(?:eqnarray|align|alignat|gather|multline|flalign)[*]?' ; # Environments turning on eqnarray math mode
805 # my $MATHARRREPL='eqnarray*'; # Environment introducing deleted maths blocks
806 # 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
807 # my $COUNTERCMD='(?:footnote|part|chapter|section|subsection|subsubsection|paragraph|subparagraph)'; # textcmds which are associated with a counter
808 # # If any of these commands occur in a deleted block
809 # # they will be succeeded by an \addtocounter{...}{-1}
810 # # for the associated counter such that the overall numbers
811 # # should be the same as in the new file
812 # my $LISTENV='(?:itemize|description|enumerate)'; # list making environments - they will generally be kept
813 # my $ITEMCMD='item'; # command marking item in a list environment
814
815 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
816 my @UNSAFEMATHCMD = ( 'qedhere', 'intertext', 'begin', 'end' ); # 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 mode) deleted unsafe commands are not deleted but simply taken outside \DIFdel
817 my $MBOXINLINEMATH = 0; # if set to 1 then surround marked-up inline maths expression with \mbox ( to get around compatibility
818 # problems between some maths packages and ulem package
819
820
821 # Markup strings
822 # If at all possible, do not change these as parts of the program
823 # depend on the actual name (particularly post-processing)
824 # At the very least adapt subroutine postprocess to new tokens.
825 my $ADDMARKOPEN = '\DIFaddbegin '; # Token to mark begin of appended text
826 my $ADDMARKCLOSE = '\DIFaddend '; # Token to mark end of appended text
827 my $ADDOPEN = '\DIFadd{'; # To mark begin of added text passage
828 my $ADDCLOSE = '}'; # To mark end of added text passage
829 my $ADDCOMMENT = 'DIF > '; # To mark added comment line
830 my $DELMARKOPEN = '\DIFdelbegin '; # Token to mark begin of deleted text
831 my $DELMARKCLOSE = '\DIFdelend '; # Token to mark end of deleted text
832 my $DELOPEN = '\DIFdel{'; # To mark begin of deleted text passage
833 my $DELCLOSE = '}'; # To mark end of deleted text passage
834 my $DELCMDOPEN = '%DIFDELCMD < '; # To mark begin of deleted commands (must begin with %, i.e., be a comment
835 my $DELCMDCLOSE = "%%%\n"; # To mark end of deleted commands (must end with a new line)
836 my $AUXCMD = '%DIFAUXCMD'; # follows auxiliary commands put in by latexdiff to make difference file legal
837 # auxiliary commands must be on a line of their own
838 # Note that for verbatim environment openings the %DIFAUXCMD cannot be placed in
839 # the same line as this would mean they are shown
840 # so the special form "%DIFAUXCMD NEXT" is used to indicate that the next line
841 # is an auxiliary command
842 # Similarly "%DIFAUXCMD LAST" would indicate the auxiliary command is in previous line (not currently used)
843 my $DELCOMMENT = 'DIF < '; # To mark deleted comment line
844 my $VERBCOMMENT = 'DIFVRB '; # to mark lines which are within a verbatim environment
845
846 # main local variables:
847 my @TEXTCMDLIST = (); # array containing patterns of commands with text arguments
848 my @TEXTCMDEXCL = (); # array containing patterns of commands without text arguments (if a pattern
849 # matches both TEXTCMDLIST and TEXTCMDEXCL it is excluded)
850 my @CONTEXT1CMDLIST = (); # array containing patterns of commands with text arguments (subset of text commands),
851 # but which cause confusion if used out of context (e.g. \caption).
852 # In deleted passages, the command will be disabled but its argument is marked up
853 # Otherwise they behave exactly like TEXTCMD's
854 my @CONTEXT1CMDEXCL = (); # exclude list for above, but always empty
855 my @CONTEXT2CMDLIST = (); # array containing patterns of commands with text arguments, but which fail or cause confusion
856 # if used out of context (e.g. \title). They and their arguments will be disabled in deleted
857 # passages
858 my @CONTEXT2CMDEXCL = (); # exclude list for above, but always empty
859 my @MATHTEXTCMDLIST = (); # treat like textcmd. If a textcmd is in deleted or added block, just wrap the
860 # whole content with \DIFadd or \DIFdel irrespective of content. This functionality
861 # is useful for pseudo commands \MATHBLOCK.. into which math environments are being
862 # transformed
863 my @MATHTEXTCMDEXCL = (); #
864
865 # Note I need to declare this with "our" instead of "my" because later in the code I have to "local"ise these
866 our @SAFECMDLIST = (); # array containing patterns of safe commands (which do not break when in the argument of DIFadd or DIFDEL)
867 our @SAFECMDEXCL = ();
868 my @MBOXCMDLIST = (); # patterns for commands which are in principle safe but which need to be surrounded by an \mbox
869 my @MBOXCMDEXCL = (); # all the patterns in MBOXCMDLIST will be appended to SAFECMDLIST
870
871 my @KEEPCMDLIST = (qr/^bibitem$/); # patterns for commands which should not be deleted in nominally deleted text passages
872 my @KEEPCMDEXCL = ();
873
874 my ( $i, $j, $l );
875 my ( $old, $new );
876 my ( $line, $key );
877 my (@dumlist);
878 my ( $newpreamble, $oldpreamble );
879 my ( @newpreamble, @oldpreamble, @diffpreamble, @diffbody );
880 my ($latexdiffpreamble);
881 my ( $oldbody, $newbody, $diffbo );
882 my ( $oldpost, $newpost );
883 my ($diffall);
884 #<<< format skipping: do not let perltidy change my formatting
885 # Option names
886 my ($type,$subtype,$floattype,$config,$preamblefile,$encoding,$nolabel,$visiblelabel,
887 $filterscript,$ignorefilterstderr,
888 $showpreamble,$showsafe,$showtext,$showconfig,$showall,
889 $replacesafe,$appendsafe,$excludesafe,
890 $replacetext,$appendtext,$excludetext,
891 $replacecontext1,$appendcontext1,
892 $replacecontext2,$appendcontext2,
893 $help,$verbose,$driver,$version,$ignorewarnings,
894 $onlyadditions,
895 $enablecitmark,$disablecitmark,$allowspaces,$flatten,$nolinks,$debug,$earlylatexdiffpreamble); ###$disablemathmark,
896 #>>>
897 my ($mboxsafe);
898 # MNEMNONICS for mathmarkup
899 my $mathmarkup;
900 use constant {
901 OFF => 0,
902 WHOLE => 1,
903 COARSE => 2,
904 FINE => 3
905 };
906 # MNEMNONICS for graphicsmarkup
907 my $graphicsmarkup;
908 use constant {
909 NONE => 0,
910 NEWONLY => 1,
911 BOTH => 2
912 };
913
914 my ($mboxcmd);
915 #<<< format skipping: do not let perltidy change my formatting
916 my (@configlist,@addtoconfiglist,@labels,
917 @appendsafelist,@excludesafelist,
918 @appendmboxsafelist,@excludemboxsafelist,
919 @appendtextlist,@excludetextlist,
920 @appendcontext1list,@appendcontext2list,
921 @packagelist);
922 #>>>
923 my ( $assign, @config );
924 # Hash where keys corresponds to the names of all included packages (including the documentclass as another package
925 # the optional arguments to the package are the values of the hash elements
926 my ( $pkg, %packages );
927
928 # Global variables for keeping state across subroutines
929 our $suppress_markup = 0; # 0: do not block markup, 1: block markup (supporting DIFNOMARKUP directives)
930
931 # Defaults
932 $mathmarkup = COARSE;
933 $verbose = 0;
934 $onlyadditions = 0;
935 # output debug and intermediate files, set to 0 in final distribution
936 $debug = 0;
937 # insert preamble directly after documentclass - experimental feature, set to 0 in final distribution
938 # Note that this failed with mini example (or other files, where packages used in latexdiff preamble
939 # are called again with incompatible options in preamble of resulting file)
940 $earlylatexdiffpreamble = 0;
941
942 # define character properties
943 sub IsNonAsciiPunct {
944 return <<'END' # Unicode punctuation but excluding ASCII punctuation
945 +utf8::IsPunct
946 -utf8::IsASCII
947 END
948 }
949
950 sub IsNonAsciiS {
951 return <<'END' # Unicode symbol but excluding ASCII
952 +utf8::IsS
953 -utf8::IsASCII
954 END
955 }
956
957 my %verbhash;
958
959 Getopt::Long::Configure('bundling');
960 GetOptions(
961 'type|t=s' => \$type,
962 'subtype|s=s' => \$subtype,
963 'floattype|f=s' => \$floattype,
964 'config|c=s' => \@configlist,
965 'add-to-config=s' => \@addtoconfiglist,
966 'preamble|p=s' => \$preamblefile,
967 'encoding|e=s' => \$encoding,
968 'label|L=s' => \@labels,
969 'no-label' => \$nolabel,
970 'visible-label' => \$visiblelabel,
971 'exclude-safecmd|A=s' => \@excludesafelist,
972 'replace-safecmd=s' => \$replacesafe,
973 'append-safecmd|a=s' => \@appendsafelist,
974 'exclude-textcmd|X=s' => \@excludetextlist,
975 'replace-textcmd=s' => \$replacetext,
976 'append-textcmd|x=s' => \@appendtextlist,
977 'replace-context1cmd=s' => \$replacecontext1,
978 'append-context1cmd=s' => \@appendcontext1list,
979 'replace-context2cmd=s' => \$replacecontext2,
980 'append-context2cmd=s' => \@appendcontext2list,
981 'exclude-mboxsafecmd=s' => \@excludemboxsafelist,
982 'append-mboxsafecmd=s' => \@appendmboxsafelist,
983 'show-preamble' => \$showpreamble,
984 'show-safecmd' => \$showsafe,
985 'show-textcmd' => \$showtext,
986 'show-config' => \$showconfig,
987 'show-all' => \$showall,
988 'packages=s' => \@packagelist,
989 'allow-spaces' => \$allowspaces,
990 'math-markup=s' => \$mathmarkup,
991 'graphics-markup=s' => \$graphicsmarkup,
992 'enable-citation-markup|enforce-auto-mbox' => \$enablecitmark,
993 'disable-citation-markup|disable-auto-mbox' => \$disablecitmark,
994 'verbose|V' => \$verbose,
995 'ignore-warnings' => \$ignorewarnings,
996 'driver=s' => \$driver,
997 'flatten' => \$flatten,
998 'filter-script=s' => \$filterscript,
999 'ignore-filter-stderr' => \$ignorefilterstderr,
1000 'no-links' => \$nolinks,
1001 'no-del' => \$onlyadditions,
1002 'version' => \$version,
1003 'help|h' => \$help,
1004 'debug!' => \$debug
1005 ) or die "Use latexdiff -h to get help.\n";
1006
1007 if ($help) {
1008 usage();
1009 }
1010
1011 if ($version) {
1012 print STDERR $versionstring;
1013 exit 0;
1014 }
1015
1016 print STDERR $versionstring if $verbose;
1017
1018 if ( defined($showall) ) {
1019 $showpreamble = $showsafe = $showtext = $showconfig = 1;
1020 }
1021 # Default types
1022 $type = 'UNDERLINE' unless defined($type);
1023 $subtype = 'SAFE' unless defined($subtype);
1024 # set floattype to IDENTICAL for LABEL and ONLYCHANGEDPAGE subtype, unless it has been set explicitly on the command line
1025 $floattype = ( $subtype eq 'LABEL' || $subtype eq 'ONLYCHANGEDPAGE' ) ? 'IDENTICAL' : 'FLOATSAFE'
1026 unless defined($floattype);
1027 if ( $subtype eq 'LABEL' ) {
1028 print STDERR "Note that LABEL subtype is deprecated. If possible, use ZLABEL instead (requires zref package)";
1029 }
1030
1031 if ( defined($mathmarkup) ) {
1032 $mathmarkup =~ tr/a-z/A-Z/;
1033 if ( $mathmarkup eq 'OFF' ) {
1034 $mathmarkup = OFF;
1035 } elsif ( $mathmarkup eq 'WHOLE' ) {
1036 $mathmarkup = WHOLE;
1037 } elsif ( $mathmarkup eq 'COARSE' ) {
1038 $mathmarkup = COARSE;
1039 } elsif ( $mathmarkup eq 'FINE' ) {
1040 $mathmarkup = FINE;
1041 } elsif ( $mathmarkup !~ m/^[0123]$/ ) {
1042 die "latexdiff Illegal value: ($mathmarkup) for option--math-markup. Possible values: OFF,WHOLE,COARSE,FINE,0-3\n";
1043 }
1044 # else use numerical value
1045 }
1046
1047 # Give filterscript a default empty string
1048 $filterscript = "" unless defined($filterscript);
1049
1050 # setting extra preamble commands
1051 if ( defined($preamblefile) ) {
1052 $latexdiffpreamble = join "\n", ( extrapream($preamblefile), "" );
1053 } else {
1054 $latexdiffpreamble = join "\n", ( extrapream( $type, $subtype, $floattype ), "" );
1055 }
1056
1057 my $preamble_no_comments = $latexdiffpreamble;
1058 $preamble_no_comments =~ s/(?<!\\)%.*$//mg; # version of preamble stripped of all comments
1059
1060 if ( defined($driver) ) {
1061 # for changebar only
1062 $latexdiffpreamble =~ s/\[pdftex\]/[$driver]/sg unless defined($preamblefile);
1063 }
1064 # setting up @SAFECMDLIST and @SAFECMDEXCL
1065 if ( defined($replacesafe) ) {
1066 init_regex_arr_ext( \@SAFECMDLIST, $replacesafe );
1067 } else {
1068 init_regex_arr_data( \@SAFECMDLIST, "SAFE COMMANDS" );
1069 }
1070 foreach $appendsafe (@appendsafelist) {
1071 init_regex_arr_ext( \@SAFECMDLIST, $appendsafe );
1072 }
1073 foreach $excludesafe (@excludesafelist) {
1074 init_regex_arr_ext( \@SAFECMDEXCL, $excludesafe );
1075 # add explicit list to unsafe math commands also
1076 init_regex_arr_ext( \@UNSAFEMATHCMD, $excludesafe );
1077 }
1078 # setting up @MBOXCMDLIST and @MBOXCMDEXCL
1079 foreach $mboxsafe (@appendmboxsafelist) {
1080 init_regex_arr_ext( \@MBOXCMDLIST, $mboxsafe );
1081 }
1082 foreach $mboxsafe (@excludemboxsafelist) {
1083 init_regex_arr_ext( \@MBOXCMDEXCL, $mboxsafe );
1084 }
1085
1086 # setting up @TEXTCMDLIST and @TEXTCMDEXCL
1087 if ( defined($replacetext) ) {
1088 init_regex_arr_ext( \@TEXTCMDLIST, $replacetext );
1089 } else {
1090 init_regex_arr_data( \@TEXTCMDLIST, "TEXT COMMANDS" );
1091 }
1092 foreach $appendtext (@appendtextlist) {
1093 init_regex_arr_ext( \@TEXTCMDLIST, $appendtext );
1094 }
1095 foreach $excludetext (@excludetextlist) {
1096 init_regex_arr_ext( \@TEXTCMDEXCL, $excludetext );
1097 }
1098
1099 # setting up @CONTEXT1CMDLIST ( @CONTEXT1CMDEXCL exist but is always empty )
1100 if ( defined($replacecontext1) ) {
1101 init_regex_arr_ext( \@CONTEXT1CMDLIST, $replacecontext1 );
1102 } else {
1103 init_regex_arr_data( \@CONTEXT1CMDLIST, "CONTEXT1 COMMANDS" );
1104 }
1105 foreach $appendcontext1 (@appendcontext1list) {
1106 init_regex_arr_ext( \@CONTEXT1CMDLIST, $appendcontext1 );
1107 }
1108
1109 # setting up @CONTEXT2CMDLIST ( @CONTEXT2CMDEXCL exist but is always empty )
1110 if ( defined($replacecontext2) ) {
1111 init_regex_arr_ext( \@CONTEXT2CMDLIST, $replacecontext2 );
1112 } else {
1113 init_regex_arr_data( \@CONTEXT2CMDLIST, "CONTEXT2 COMMANDS" );
1114 }
1115 foreach $appendcontext2 (@appendcontext2list) {
1116 init_regex_arr_ext( \@CONTEXT2CMDLIST, $appendcontext2 );
1117 }
1118
1119 # setting configuration variables
1120 @config = ();
1121 foreach $config (@configlist) {
1122 if ( -f $config || lc $config eq '/dev/null' ) {
1123 open( FILE, $config ) or die("Couldn't open configuration file $config: $!");
1124 while (<FILE>) {
1125 chomp;
1126 next if /^\s*#/ || /^\s*%/ || /^\s*$/;
1127 push( @config, $_ );
1128 }
1129 close(FILE);
1130 } else {
1131 # foreach ( split(",",$config) ) {
1132 # push @config,$_;
1133 # }
1134 push @config, split( ",", $config );
1135 }
1136 }
1137 foreach $assign (@config) {
1138 $assign =~ m/\s*(\w*)\s*=\s*(\S*)\s*$/
1139 or die "Illegal assignment $assign in configuration list (must be variable=value)";
1140 exists $CONFIG{$1} or die "Unknown configuration variable $1.";
1141 $CONFIG{$1} = $2;
1142 }
1143
1144 my @addtoconfig = ();
1145 foreach $config (@addtoconfiglist) {
1146 if ( -f $config || lc $config eq '/dev/null' ) {
1147 open( FILE, $config ) or die("Couldn't open addd-to-config file $config: $!");
1148 while (<FILE>) {
1149 chomp;
1150 next if /^\s*#/ || /^\s*%/ || /^\s*$/;
1151 push( @addtoconfig, $_ );
1152 }
1153 close(FILE);
1154 } else {
1155 # foreach ( split(",",$config) ) {
1156 # push @addtoconfig,$_;
1157 # }
1158 push @addtoconfig, split( ",", $config );
1159 }
1160 }
1161
1162 # initialise default lists from DATA
1163 # for those configuration variables, which have not been set explicitly, initiate from list in document
1164 foreach $key ( keys(%CONFIG) ) {
1165 if ( !defined $CONFIG{$key} ) {
1166 @dumlist = ();
1167 init_regex_arr_data( \@dumlist, "$key CONFIG" );
1168 $CONFIG{$key} = join( ";", @dumlist );
1169 }
1170 }
1171
1172 foreach $assign (@addtoconfig) {
1173 ###print STDERR "assign:|$assign|\n";
1174 $assign =~ m/\s*(\w*)\s*=\s*(\S*)\s*$/
1175 or die "Illegal assignment $assign in configuration list (must be variable=value)";
1176 exists $CONFIG{$1} or die "Unknown configuration variable $1.";
1177 $CONFIG{$1} .= ";$2";
1178 }
1179
1180 # Map from hash to variables (we do this to have more concise code later, change from comma-separated list)
1181 foreach ( keys(%CONFIG) ) {
1182 if ( $_ eq "MINWORDSBLOCK" ) { $MINWORDSBLOCK = $CONFIG{$_}; }
1183 elsif ( $_ eq "MAXCHANGESLETTER" ) { $MAXCHANGESLETTER = $CONFIG{$_}; }
1184 elsif ( $_ eq "FLOATENV" ) { $FLOATENV = liststringtoregex( $CONFIG{$_} ); }
1185 elsif ( $_ eq "ITEMCMD" ) { $ITEMCMD = $CONFIG{$_}; }
1186 elsif ( $_ eq "LISTENV" ) { $LISTENV = liststringtoregex( $CONFIG{$_} ); }
1187 elsif ( $_ eq "PICTUREENV" ) { $PICTUREENV = liststringtoregex( $CONFIG{$_} ); }
1188 elsif ( $_ eq "MATHENV" ) { $MATHENV = liststringtoregex( $CONFIG{$_} ); }
1189 elsif ( $_ eq "MATHREPL" ) { $MATHREPL = $CONFIG{$_}; }
1190 elsif ( $_ eq "MATHARRENV" ) { $MATHARRENV = liststringtoregex( $CONFIG{$_} ); }
1191 elsif ( $_ eq "ARRENV" ) { $ARRENV = liststringtoregex( $CONFIG{$_} ); }
1192 elsif ( $_ eq "VERBATIMENV" ) { $VERBATIMENV = liststringtoregex( $CONFIG{$_} ); }
1193 elsif ( $_ eq "VERBATIMLINEENV" ) { $VERBATIMLINEENV = liststringtoregex( $CONFIG{$_} ); }
1194 elsif ( $_ eq "CUSTOMDIFCMD" ) { $CUSTOMDIFCMD = liststringtoregex( $CONFIG{$_} ); }
1195 elsif ( $_ eq "COUNTERCMD" ) { $COUNTERCMD = liststringtoregex( $CONFIG{$_} ); }
1196 elsif ( $_ eq "SCALEDELGRAPHICS" ) { $SCALEDELGRAPHICS = $CONFIG{$_}; }
1197 elsif ( $_ eq "MATHARRREPL" ) {
1198 $MATHARRREPL = $CONFIG{$_};
1199 print STDERR
1200 "WARNING: Setting MATHARRREPL is depracated. Generally deleted math array environments will be set to their starred varieties and the setting of MATHARREPL is ignored.\n\n"
1201 unless $MATHARRREPL =~ /eqnarray\*/;
1202 } else {
1203 die "Unknown configuration variable $_.";
1204 }
1205 }
1206
1207 if ( $mathmarkup == COARSE || $mathmarkup == WHOLE ) {
1208 push( @MATHTEXTCMDLIST, qr/^MATHBLOCK(?:$MATHENV|$MATHARRENV|SQUAREBRACKET)$/ );
1209 }
1210
1211
1212 foreach $pkg (@packagelist) {
1213 map { $packages{$_} = "" } split( /,/, $pkg );
1214 }
1215
1216 if ( $showconfig || $showtext || $showsafe || $showpreamble ) {
1217 # only quit here if no other argument is given
1218 # otherwse delay showing the coniguration as it can be modified depending on what is found in the input files
1219 if ( @ARGV == 0 ) {
1220 print "%Simple configuration with standard pre-set parameters only:\n";
1221 print "% [Provide sample input and output files with the --show... option to get full configuration:]\n";
1222
1223 show_configuration();
1224 exit 0;
1225 }
1226 }
1227
1228 if ( @ARGV != 2 ) {
1229 print STDERR "2 and only 2 non-option arguments required. Write latexdiff -h to get help\n";
1230 exit(2);
1231 }
1232
1233 # Are extra spaces between command arguments permissible?
1234 my $extraspace;
1235 if ($allowspaces) {
1236 $extraspace = '\s*';
1237 } else {
1238 $extraspace = '';
1239 }
1240
1241 # append context lists to text lists (as text property is implied)
1242 push @TEXTCMDLIST, qr/^(SUPER|SUB)SCRIPT$/;
1243
1244 push @TEXTCMDLIST, @CONTEXT1CMDLIST;
1245 push @TEXTCMDLIST, @CONTEXT2CMDLIST;
1246
1247 push @TEXTCMDLIST, @MATHTEXTCMDLIST if $mathmarkup == COARSE;
1248
1249 # internal additions to SAFECMDLIST
1250 push( @SAFECMDLIST, qr/^QLEFTBRACE$/, qr/^QRIGHTBRACE$/ );
1251
1252 # Patterns. These are used by some of the subroutines, too
1253 # I can only define them down here because value of extraspace depends on an option
1254
1255 my $pat0 = '(?:[^{}])*';
1256 my $pat_n = $pat0;
1257 # if you get "undefined control sequence MATHBLOCKmath" error, increase the maximum value in this loop
1258 for ( my $i_pat = 0 ; $i_pat < 20 ; ++$i_pat ) {
1259 $pat_n = '(?:[^{}]|\{' . $pat_n . '\}|\\\\\{|\\\\\})*';
1260 # Actually within the text body, quoted braces are replaced in pre-processing. The only place where
1261 # the last part of the pattern matters is when processing the arguments of context2cmds in the preamble
1262 # and these contain a \{ or \} combination, probably rare.
1263 # It should thus be fine to use the simpler version below.
1264 ### $pat_n = '(?:[^{}]|\{'.$pat_n.'\})*';
1265 }
1266
1267 my $brat0 = '(?:[^\[\]]|\\\[|\\\])*';
1268 my $brat_n = $brat0;
1269 for ( my $i_pat = 0 ; $i_pat < 4 ; ++$i_pat ) {
1270 $brat_n = '(?:[^\[\]]|\[' . $brat_n . '\]|\\\[|\\\])*';
1271 ### $brat_n = '(?:[^\[\]]|\['.$brat_n.'\])*'; # Version not taking into account escaped \[ and \]
1272 }
1273 my $abrat0 = '(?:[^<>])*';
1274
1275
1276 # variable definitions are in order that they are matched
1277 my $and = '&';
1278 my $quotemarks = '(?:\'\')|(?:\`\`)';
1279 # some common abbreviations involving punctuations within them. They need special treatment because otherwise in some
1280 # circumstances the ignoring of white space differences in conjunction with merging according to MINWORDSBLOCK rule
1281 # could turn 'i.e.' into 'i.\PAR e.' (see https://github.com/ftilmann/latexdiff/issues/269)
1282 # English: i.e., e.g. Deutsch: z.B.
1283 my $abbreviation = '(?:i\. ?e\.|e\. ?g\.|z\. ?B\.)';
1284 my $number = '-?\d*\.\d*';
1285
1286 # word: sequence of letters or accents followed by letter
1287 my $word_cj = '\p{Han}|\p{InHiragana}|\p{InKatakana}';
1288 my $word = '(?:' . $word_cj . '|(?:(?:[-\w\d*]|\\\\[\"\'\`~^][A-Za-z\*])(?!(?:' . $word_cj . ')))+)';
1289
1290 # quoted underscore - this needs special treatment as perl treats _ as a letter (\w) but latex does not
1291 # such that a\_b would otherwise be interpreted as a{\_}b by latex but a{\_b} by latexdiff
1292 my $quotedunderscore = '\\\\_';
1293 # Handle tex \def macro: \def\MAKRONAME#1[#2]#3{DEFINITION}
1294 my $defseq = '\\\\def\\\\[\w\d@\*]+(?:#\d+|\[#\d+\])+(?:\{' . $pat_n . '\})?';
1295 my $cmdleftright = '\\\\(?:left|right|[Bb]igg?[lrm]?|middle)\s*(?:[<>()\[\]|\.]|\\\\(?:[|{}]|\w+))';
1296
1297 # for selected commands, the number of arguments is known, and we can therefore allow spaces between command and its argument
1298 # 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
1299 my $predefinedcmdoptseq12 = '\\\\(?:href|bibfield|bibinfo)\s*(?:\[' . $brat_n . '\])?\s*(?:\{' . $pat_n . '\}\s*){2}'; # Commands with one optional and two non-optional arguments
1300 my $predefinedcmdoptseq01 = '\\\\(?:url|BibitemShut)\s*\s*(?:\{' . $pat_n . '\}\s*){1}'; # Commands with one non-optional argument
1301 # \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.
1302 my $predefinedbibitem =
1303 '\\\\(?:bibitem)\s*(?:\[' . $brat_n . '\])?\s*(?:\{' . $pat_n . '\})(?:%?\s*\\\\BibitemOpen)?'; # Commands with one optional and one non-optional arguments
1304 my $predefinedcmdoptseq =
1305 '(?:' . $predefinedcmdoptseq12 . '|' . $predefinedcmdoptseq01 . '|' . $predefinedbibitem . ')';
1306
1307 # standard $cmdoptseq (default: no intrevening spaces, controlled by extraspace) - a final open parentheses is merged to the command if it exists to deal properly with multi-argument text command
1308 my $coords = '[\-.,\s\d]*';
1309 #<<< format skipping: do not let perltidy change my formatting
1310 my $cmdoptseq='(?:\\\\protect)?\\\\[\w\d@\*]+'.$extraspace.
1311 '(?:(?:<'.$abrat0.'>|\['.$brat_n.'\]|\{'. $pat_n . '\}|\(' . $coords .'\))'.$extraspace.')*\{?';
1312 #>>>
1313
1314 # inline math $....$ or \(..\)
1315 my $math = '\$(?:[^$]|\\\$)*?\$|\\\\[(](?:.|\n)*?\\\\[)]';
1316 ## the current maths command cannot cope with newline within the math expression
1317
1318 my $backslashnl = '\\\\\n';
1319 my $oneletcmd = '\\\\.\*?(?:\[' . $brat_n . '\]|\{' . $pat_n . '\})*';
1320 my $comment = '%[^\n]*\n';
1321 my $punct = '[0.,\/\'\`:;\"\?\(\)\[\]!~\p{IsNonAsciiPunct}\p{IsNonAsciiS}]';
1322 my $mathpunct = '[+=<>\-\|]';
1323
1324 # Assembled pattern
1325 my $pat =
1326 qr/(?:\A\s*)?(?:${abbreviation}|${and}|${quotemarks}|${number}|${word}|$quotedunderscore|${defseq}|$cmdleftright|${predefinedcmdoptseq}|${cmdoptseq}|${math}|${backslashnl}|${oneletcmd}|${comment}|${punct}|${mathpunct}|\{|\})\s*/;
1327
1328 # now we are done setting up and can start working
1329 my ( $oldfile, $newfile ) = @ARGV;
1330 # check for existence of input files
1331 if ( !-e $oldfile ) {
1332 die "Input file $oldfile does not exist";
1333 }
1334 if ( !-e $newfile ) {
1335 die "Input file $newfile does not exist";
1336 }
1337
1338 # set the labels to be included into the file
1339 # first find out which file name is longer for correct alignment
1340 my ( $diff, $oldlabel_n_spaces, $newlabel_n_spaces );
1341 $oldlabel_n_spaces = 0;
1342 $newlabel_n_spaces = 0;
1343 $diff = length($newfile) - length($oldfile);
1344 if ( $diff > 0 ) {
1345 $oldlabel_n_spaces = $diff;
1346 }
1347 if ( $diff < 0 ) {
1348 $newlabel_n_spaces = abs($diff);
1349 }
1350
1351 my ( $oldtime, $newtime, $oldlabel, $newlabel );
1352 if ( defined( $labels[0] ) ) {
1353 $oldlabel = $labels[0];
1354 } else {
1355 $oldtime = localtime( ( stat($oldfile) )[9] );
1356 $oldlabel = "$oldfile " . " " x ($oldlabel_n_spaces) . $oldtime;
1357 }
1358 if ( defined( $labels[1] ) ) {
1359 $newlabel = $labels[1];
1360 } else {
1361 $newtime = localtime( ( stat($newfile) )[9] );
1362 $newlabel = "$newfile " . " " x ($newlabel_n_spaces) . $newtime;
1363 }
1364
1365 $encoding = guess_encoding($newfile) unless defined($encoding);
1366
1367 $encoding = "utf8" if $encoding =~ m/^utf8/i;
1368 print STDERR "Encoding $encoding\n" if $verbose;
1369 if ( lc($encoding) eq "utf8" ) {
1370 binmode( STDOUT, ":utf8" );
1371 binmode( STDERR, ":utf8" );
1372 }
1373
1374 # filter($text)
1375 # Runs $text through the script provided in $filterscript argument, if set
1376 # If not set, just returns $text unchanged.
1377 # If flatten was set, defer filtering to flatten. flatten will run the filter
1378 # on all incoming text prior to its own processing.
1379 # If flatten was not set, filter each of old and new once (see just below this def)
1380 sub filter {
1381 my ($text) = @_;
1382 my ( $textout, $pid );
1383 if ( $filterscript ne "" ) {
1384 print STDERR "Passing " . length($text) . " chars to filter script " . $filterscript . "\n" if $verbose;
1385
1386 if ($ignorefilterstderr) {
1387 # If we need to capture and bury STDERR, use the Open3 version, and close CHLD_ERR below.
1388 use IPC::Open3;
1389 # We consume STDERR from the process, and hide it
1390 $pid = open3( \*CHLD_IN, \*CHLD_OUT, \*CHLD_ERR, $filterscript ) or die "open3() failed $!";
1391 } else {
1392 # Capture STDOUT and use as our new $text. Allow STDERR to go to console.
1393 use IPC::Open2;
1394 $pid = open2( \*CHLD_OUT, \*CHLD_IN, $filterscript ) or die "open2() failed $!";
1395 }
1396 # Send in $text
1397 print CHLD_IN $text . "\n"; # Adding a newline just to make sure there is one.
1398 close CHLD_IN;
1399 # Wait for output and gather it up
1400 while (<CHLD_OUT>) {
1401 $textout = $textout . $_;
1402 }
1403 if ($ignorefilterstderr) {
1404 close CHLD_ERR; # Enable only if Open3 used above
1405 }
1406 # On the off chance a very long running and/or frequently called script is used.
1407 waitpid( $pid, 0 );
1408 $text = $textout;
1409 print STDERR "Received " . length($text) . " chars after filtering\n" if $verbose;
1410 print STDERR $text if $verbose;
1411 }
1412 return $text;
1413 }
1414
1415 $old = read_file_with_encoding( $oldfile, $encoding );
1416 $new = read_file_with_encoding( $newfile, $encoding );
1417
1418 if ( not defined($flatten) ) {
1419 $old = filter($old);
1420 $new = filter($new);
1421 }
1422
1423
1424
1425 # reset time
1426 exetime(1);
1427 ( $oldpreamble, $oldbody, $oldpost ) = splitdoc( $old, '\\\\begin\{document\}', '\\\\end\{document\}' );
1428
1429 ( $newpreamble, $newbody, $newpost ) = splitdoc( $new, '\\\\begin\{document\}', '\\\\end\{document\}' );
1430
1431 ## if ($encoding ne $1 ) {
1432
1433 if ($flatten) {
1434 $oldbody = flatten( $oldbody, $oldpreamble, File::Spec->rel2abs($oldfile), $encoding );
1435 $newbody = flatten( $newbody, $newpreamble, File::Spec->rel2abs($newfile), $encoding );
1436 # flatten preamble
1437 $oldpreamble = flatten( $oldpreamble, $oldpreamble, File::Spec->rel2abs($oldfile), $encoding );
1438 $newpreamble = flatten( $newpreamble, $newpreamble, File::Spec->rel2abs($newfile), $encoding );
1439
1440 }
1441
1442 my @auxlines;
1443
1444 # boolean variab
1445 my ($ulem) = 0;
1446
1447 if ( length $oldpreamble && length $newpreamble ) {
1448 # pre-process preamble by looking for commands used in \maketitle (title, author, date etc commands)
1449 # and marking up content with latexdiff markup
1450 @auxlines = preprocess_preamble( $oldpreamble, $newpreamble );
1451
1452 @oldpreamble = split /\n/, $oldpreamble;
1453 @newpreamble = split /\n/, $newpreamble;
1454
1455 # If a command is defined in the preamble of the new file, and only uses safe commands, then it can be considered to be safe) (contribution S. Gouezel)
1456 # Base this assessment on the new preamble
1457 add_safe_commands($newpreamble);
1458
1459 # get a list of packages from preamble if not predefined
1460 %packages = list_packages($newpreamble) unless %packages;
1461 if ( %packages && $debug ) {
1462 my $key;
1463 foreach $key ( keys %packages ) { print STDERR "DEBUG \\usepackage[", $packages{$key}, "]{", $key, "}\n"; }
1464 }
1465 }
1466
1467 # have to return to all processing to properly add preamble additions based on packages found
1468 if ( defined($graphicsmarkup) ) {
1469 $graphicsmarkup =~ tr/a-z/A-Z/;
1470 if ( $graphicsmarkup eq 'OFF' or $graphicsmarkup eq 'NONE' ) {
1471 $graphicsmarkup = NONE;
1472 } elsif ( $graphicsmarkup eq 'NEWONLY' or $graphicsmarkup eq 'NEW-ONLY' ) {
1473 $graphicsmarkup = NEWONLY;
1474 } elsif ( $graphicsmarkup eq 'BOTH' ) {
1475 $graphicsmarkup = BOTH;
1476 } elsif ( $graphicsmarkup !~ m/^[012]$/ ) {
1477 die
1478 "latexdiff Illegal value: ($graphicsmarkup) for option --highlight-graphics. Possible values: OFF,WHOLE,COARSE,FINE,0-2\n";
1479 }
1480 # else use numerical value
1481 } else {
1482 # Default: no explicit setting in menu
1483 if ( defined $packages{"graphicx"} or defined $packages{"graphics"} ) {
1484 $graphicsmarkup = NEWONLY;
1485 } else {
1486 $graphicsmarkup = NONE;
1487 }
1488 }
1489
1490 if ( defined $packages{"hyperref"} ) {
1491 # deleted lines should not generate or appear in link names:
1492 print STDERR "hyperref package detected.\n" if $verbose;
1493 $latexdiffpreamble =~ s/\{\\DIFadd\}/{\\DIFaddtex}/g;
1494 $latexdiffpreamble =~ s/\{\\DIFdel\}/{\\DIFdeltex}/g;
1495 $latexdiffpreamble .= join "\n", ( extrapream("HYPERREF"), "" );
1496 if ($nolinks) {
1497 $latexdiffpreamble .= "\n\\hypersetup{bookmarks=false}";
1498 }
1499 ### $latexdiffpreamble .= '%DIF PREAMBLE EXTENSION ADDED BY LATEXDIFF FOR HYPERREF PACKAGE' . "\n";
1500 ### $latexdiffpreamble .= '\providecommand{\DIFadd}[1]{\texorpdfstring{\DIFaddtex{#1}}{#1}}' . "\n";
1501 ### $latexdiffpreamble .= '\providecommand{\DIFdel}[1]{\texorpdfstring{\DIFdeltex{#1}}{}}' . "\n";
1502 ### $latexdiffpreamble .= '%DIF END PREAMBLE EXTENSION ADDED BY LATEXDIFF FOR HYPERREF PACKAGE' . "\n";
1503 }
1504
1505 # add commands for figure highlighting to preamble
1506 if ( $graphicsmarkup != NONE ) {
1507 my @matches;
1508 # Check if \DIFaddbeginFL definition calls \DIFaddbegin - if so we will issue an error message that graphics highlighting is
1509 # is not compatible with this.
1510 # (A more elegant solution would be to suppress the redefinitions of the \DIFaddbeginFL etc commands, but for this narrow use case
1511 # I currently don't see this as an efficient use of time)
1512 ### The foreach loop does not make sense here. I don't know why I put this in - (F Tilmann)
1513 ###foreach my $cmd ( "DIFaddbegin","DIFaddend","DIFdelbegin","DIFdelend" ) {
1514 @matches = ( $latexdiffpreamble =~ m/command\{\\DIFaddbeginFL}\{($pat_n)}/sg );
1515 # we look at the last one of the list to take into account possible redefinition but almost always matches should have exactly one element
1516 if ( $matches[$#matches] =~ m/\\DIFaddbegin/ ) {
1517 die
1518 "Cannot combine graphics markup with float styles defining \\DIFaddbeginFL in terms of \\DIFaddbegin. Use --graphics-markup=none option or choose a different float style.";
1519 exit 10;
1520 }
1521 ###}
1522 $latexdiffpreamble .= join "\n",
1523 ( "\\providecommand{\\DIFscaledelfig}{$SCALEDELGRAPHICS}", extrapream("HIGHLIGHTGRAPHICS"), "" )
1524 # unless $preamble_no_comments =~ m/\{\\DIFdelgraphicsbox\}/ ;
1525 unless $preamble_no_comments =~ m/\{\\(?:DIFdelgraphicsbox|DIFdelgraphicswidth|DIFdelgraphicsheight)\}/;
1526
1527 # only change required for highlighting both is to declare \includegraphics safe, as preamble already contains commands for deleted environment
1528 if ( $graphicsmarkup == BOTH ) {
1529 init_regex_arr_list( \@SAFECMDLIST, 'includegraphics' );
1530 }
1531 }
1532
1533 $ulem = ( $latexdiffpreamble =~ /\\RequirePackage(?:\[$brat_n\])?\{ulem\}/ || defined $packages{"ulem"} );
1534
1535 # If amsmath is defined and $ulem is used for markup, redefine the \sout command to also work (mostly) in math mode
1536 # See stack exchange https://tex.stackexchange.com/questions/20609/strikeout-in-math-mode/308647#308647 based on comment by Taylor Raine
1537 if ( defined( $packages{'amsmath'} ) and $ulem ) {
1538 $latexdiffpreamble .= join "\n", ( extrapream('AMSMATHULEM'), "" );
1539 }
1540
1541 # If listings is being used or can be found in the latexdiff search path, add to the preamble auxiliary code to enable line-by-line markup
1542 if ( defined( $packages{"listings"} ) or `kpsewhich listings.sty` ne "" ) {
1543 my @listingpreamble = extrapream("LISTINGS");
1544 if ( $latexdiffpreamble =~ /\\RequirePackage(?:\[$brat_n\])?\{color\}/ ) {
1545 @listingpreamble = extrapream("COLORLISTINGS");
1546 }
1547 my @listingDIFcode = ();
1548 my $replaced;
1549 # note that in case user supplies preamblefile the type might not reflect well the actual markup style
1550 @listingDIFcode = extrapream( "-nofail", "DIFCODE_" . $type ) unless defined($preamblefile);
1551 if ( !(@listingDIFcode) ) {
1552 # if listingDIFcode is empty try to guess a suitable one from the preamble
1553 if ( $latexdiffpreamble =~ /\\RequirePackage(?:\[$brat_n\])?\{color\}/ and $ulem ) {
1554 @listingDIFcode = extrapream("DIFCODE_UNDERLINE");
1555 } elsif ( $latexdiffpreamble =~ /\\RequirePackage(?:\[$brat_n\])?\{color\}/ ) {
1556 # only colour used
1557 @listingDIFcode = extrapream("DIFCODE_CFONT");
1558 } else {
1559 # fall-back solution
1560 @listingDIFcode = extrapream("DIFCODE_BOLD");
1561 }
1562 }
1563 # add configuration so that listings work with utf-8
1564 push @listingpreamble, '\lstset{extendedchars=\true,inputencoding=' . $encoding . "}\n";
1565
1566 # now splice it in
1567 $replaced = 0;
1568 ###print STDERR "DEBUG: listingDIFcode: ",join("\n",@listingDIFcode),"|||\n" if $debug;
1569
1570 @listingpreamble = grep {
1571 # only replace if this has not been done already (use short-circuit property of and)
1572 if ( !$replaced and $_ =~ s/^.*%DIFCODE TEMPLATE.*$/join("\n",@listingDIFcode)/e ) {
1573 ###print STDERR "DEBUG: Replaced text $_\n" if $debug;
1574 $replaced = 1;
1575 1;
1576 } else {
1577 # return false for those lines matching %DIFCODE TEMPLATE (so that they are not included in output)
1578 not m/%DIFCODE TEMPLATE/;
1579 }
1580 } @listingpreamble;
1581 ### print STDERR "DEBUG: listingpreamble @listingpreamble\n";
1582 $latexdiffpreamble .= join "\n", ( @listingpreamble, "" )
1583 unless $preamble_no_comments =~ m/\\lstnewenvironment\{DIFverbatim\}/;
1584 } else {
1585 print STDERR "WARNING: listings package not detected. Disabling mark-up in verbatim environments \n";
1586 # if listings does not exist disable line-by-line markup and treat all verbatim environments as opaque
1587 $VERBATIMENV = liststringtoregex( $CONFIG{VERBATIMENV} . ";" . $CONFIG{VERBATIMLINEENV} );
1588 $VERBATIMLINEENV = "";
1589 }
1590
1591 if ( $showconfig || $showtext || $showsafe || $showpreamble ) {
1592 # only quit here if no other argument is given
1593 # otherwse delay showing the coniguration as it can be modified depending on what is found in the input files
1594 print "%Full configuration after parsing input files and adding internal commands:\n";
1595 show_configuration();
1596 exit(0);
1597 }
1598
1599 # adding begin and end marker lines to preamble
1600 $latexdiffpreamble =
1601 "%DIF PREAMBLE EXTENSION ADDED BY LATEXDIFF\n"
1602 . $latexdiffpreamble
1603 . "%DIF END PREAMBLE EXTENSION ADDED BY LATEXDIFF\n";
1604
1605 # and return to preamble specific processing
1606 if ( length $oldpreamble && length $newpreamble ) {
1607 print STDERR "Differencing preamble.\n" if $verbose;
1608
1609 # 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
1610 unshift @newpreamble, '';
1611 unshift @oldpreamble, '';
1612 @diffpreamble = linediff( \@oldpreamble, \@newpreamble );
1613 # remove dummy line again
1614 shift @diffpreamble;
1615 # add filenames, modification time and latexdiff mark
1616 defined($nolabel)
1617 or splice @diffpreamble, 1, 0,
1618 "%DIF LATEXDIFF DIFFERENCE FILE",
1619 , "%DIF DEL $oldlabel",
1620 "%DIF ADD $newlabel";
1621 if (@auxlines) {
1622 push @diffpreamble, "%DIF DELETED TITLE COMMANDS FOR MARKUP";
1623 push @diffpreamble, join( "\n", @auxlines );
1624 }
1625 if ($earlylatexdiffpreamble) {
1626 # insert latexdiff command directly after documentclass at beginning of preamble
1627 # note that grep is only run for its side effect
1628 ( grep { s/^([^%]*\\documentclass.*)$/$1$latexdiffpreamble/ } @diffpreamble ) == 1
1629 or die "Could not find documentclass statement in preamble";
1630 } else {
1631 # insert latexdiff commands at the end of preamble (default behaviour)
1632 push @diffpreamble, $latexdiffpreamble;
1633 }
1634 push @diffpreamble, '\begin{document}';
1635 if ( defined $packages{"hyperref"} && $nolinks ) {
1636 push @diffpreamble, '\begin{NoHyper}';
1637 }
1638 } elsif ( !length $oldpreamble && !length $newpreamble ) {
1639 @diffpreamble = ();
1640 } else {
1641 print STDERR "Either both texts must have preamble or neither text must have the preamble.\n";
1642 exit(2);
1643 }
1644
1645 # Special: treat all cite commands as safe except in UNDERLINE and FONTSTRIKE mode
1646 # (there is a conflict between citation and ulem package, see
1647 # package documentation)
1648 # Use post-processing
1649 # and $packages{"apacite"}!~/natbibpapa/
1650
1651 if ( defined $packages{"units"} && $ulem ) {
1652 # protect inlined maths environments by surrounding with an \mbox
1653 # this is done to get around an incompatibility between the ulem and units package
1654 # where spaces in the argument to underlined or crossed-out \unit commands cause an error message
1655 print STDERR "units package detected at the same time as style using ulem.\n" if $verbose;
1656 $MBOXINLINEMATH = 1;
1657 }
1658
1659 if ( defined $packages{"siunitx"} ) {
1660 # protect SI command by surrounding them with an \mbox
1661 # this is done to get around an incompatibility between the ulem and siunitx package
1662 print STDERR "siunitx package detected.\n" if $verbose;
1663 my $mboxcmds = 'SI,ang,numlist,numrange,SIlist,SIrange,qty,qtylist,qtyproduct,qtyrange,complexqty,num';
1664 init_regex_arr_list( \@SAFECMDLIST, 'num,si,numproduct,unit,complexnum' );
1665 if ( $enablecitmark || ( $ulem && !$disablecitmark ) ) {
1666 init_regex_arr_list( \@MBOXCMDLIST, $mboxcmds );
1667 } else {
1668 init_regex_arr_list( \@SAFECMDLIST, $mboxcmds );
1669 }
1670 }
1671
1672 if ( defined $packages{"cleveref"} ) {
1673 # protect selected command by surrounding them with an \mbox
1674 # this is done to get around an incompatibility between ulem and cleveref package
1675 print STDERR "cleveref package detected.\n" if $verbose;
1676 my $mboxcmds = '[Cc]ref(?:range)?\*?,labelcref,(?:lc)?name[cC]refs?';
1677 if ( $enablecitmark || ( $ulem && !$disablecitmark ) ) {
1678 init_regex_arr_list( \@MBOXCMDLIST, $mboxcmds );
1679 } else {
1680 init_regex_arr_list( \@SAFECMDLIST, $mboxcmds );
1681 }
1682 }
1683
1684 if ( defined $packages{"glossaries"} ) {
1685 # protect selected command by surrounding them with an \mbox
1686 # this is done to get around an incompatibility between ulem and glossaries package
1687 print STDERR "glossaries package detected.\n" if $verbose;
1688 my $mboxcmds =
1689 '[gG][lL][sS](?:|pl|disp|link|first|firstplural|desc|user[iv][iv]?[iv]?),[aA][cC][rR](?:long|longpl|full|fullpl),[aA][cC][lfp]?[lfp]?';
1690 init_regex_arr_list( \@SAFECMDLIST,
1691 '[gG][lL][sS](?:(?:entry)?(?:text|plural|name|symbol)|displaynumberlist|entryfirst|entryfirstplural|entrydesc|entrydescplural|entrysymbolplural|entryuser[iv][iv]?[iv]?|entrynumberlist|entrydisplaynumberlist|entrylong|entrylongpl|entryshort|entryshortpl|entryfull|entryfullpl),[gG]lossentry(?:name|desc|symbol),[aA][cC][rR](?:short|shortpl),[aA]csp?'
1692 );
1693 if ( $enablecitmark || ( $ulem && !$disablecitmark ) ) {
1694 init_regex_arr_list( \@MBOXCMDLIST, $mboxcmds );
1695 } else {
1696 init_regex_arr_list( \@SAFECMDLIST, $mboxcmds );
1697 }
1698 }
1699
1700 if ( defined $packages{"chemformula"} or defined $packages{"chemmacros"} ) {
1701 print STDERR "chemformula package detected.\n" if $verbose;
1702 init_regex_arr_list( \@SAFECMDLIST, 'ch' );
1703 push( @UNSAFEMATHCMD, 'ch' );
1704 # The next command would be needed to allow highlighting the interior of \ch commands in math environments
1705 # but the redefinitions in chemformula are too deep to make this viable
1706 # push(@MATHTEXTCMDLIST,'ch');
1707 }
1708
1709 if ( defined $packages{"mhchem"} ) {
1710 print STDERR "mhchem package detected.\n" if $verbose;
1711 init_regex_arr_list( \@SAFECMDLIST, 'ce' );
1712 push( @UNSAFEMATHCMD, 'ce', 'cee' );
1713 # The next command would be needed to allow highlighting the interior of \cee commands in math environments
1714 # but the redefinitions in chemformula are too deep to make this viable
1715 # push(@MATHTEXTCMDLIST,'cee');
1716 }
1717
1718 if ( defined $packages{"tikz-dependency"} ) {
1719 init_regex_arr_ext( \@SAFECMDEXCL, 'AMPERSAND' );
1720 }
1721
1722 my ($citpat);
1723
1724 if ( defined $packages{"apacite"} ) {
1725 print STDERR "apacite package detected.\n" if $verbose;
1726 $citpat = '(?:mask)?(?:full|short|no)?cite(?:A|author|year|meta)?(?:NP)?';
1727 } elsif ( defined $packages{"biblatex"} ) {
1728 print STDERR "biblatex package detected.\n" if $verbose;
1729 $citpat = '(?:[cC]ites?|(?:[pP]aren|foot|[Tt]ext|[sS]mart|super)cites?\*?|footnotecitetex)';
1730 push( @TEXTCMDEXCL, qr/^textcite$/ );
1731 } else {
1732 # citation command pattern for all other citation schemes
1733 $citpat = '(?:cite\w*|nocite)';
1734 }
1735
1736 if ( !$ulem ) {
1737 # modes not using ulem: citation is safe
1738 push( @SAFECMDLIST, $citpat );
1739 } else {
1740 ### Experimental: disable text and emph commands
1741 push( @SAFECMDEXCL, qr/^emph$/, qr/^text..$/ );
1742 # replace \cite{..} by \mbox{\cite{..}} in added or deleted blocks in post-processing
1743 push( @MBOXCMDLIST, $citpat ) unless $disablecitmark;
1744 if ( uc($subtype) eq "COLOR" or uc($subtype) eq "DVIPSCOL" ) {
1745 # remove \cite command again from list of safe commands
1746 pop @MBOXCMDLIST;
1747 # deleted cite commands
1748 }
1749 }
1750 push( @MBOXCMDLIST, $citpat ) if $enablecitmark;
1751
1752
1753 if ( defined $packages{"amsmath"} or defined $packages{"amsart"} or defined $packages{"amsbook"} ) {
1754 print STDERR "amsmath package detected.\n" if $verbose;
1755 $MATHARRREPL = 'align*';
1756 }
1757
1758 # add commands in MBOXCMDLIST to SAFECMDLIST
1759 foreach $mboxcmd (@MBOXCMDLIST) {
1760 init_regex_arr_list( \@SAFECMDLIST, $mboxcmd );
1761 }
1762
1763 # check if \label is in SAFECMDLIST, and if yes replace "label" in $LABELCMD by something that never matches (we hope!)
1764 if ( iscmd( "label", \@SAFECMDLIST, \@SAFECMDEXCL ) ) {
1765 $LABELCMD =~ s/label/NEVERMATCHLABEL/;
1766 }
1767
1768 print STDERR "Preprocessing body. " if $verbose;
1769 preprocess( $oldbody, $newbody );
1770 writedebugfile( $oldbody, 'old-preprocess' );
1771 writedebugfile( $newbody, 'new-preprocess' );
1772
1773 # run difference algorithm
1774 @diffbody = bodydiff( $oldbody, $newbody );
1775 $diffbo = join( "", @diffbody );
1776 writedebugfile( $diffbo, "bodydiff" );
1777
1778 print STDERR "(", exetime(), " s)\n", "Postprocessing body. \n" if $verbose;
1779 postprocess($diffbo);
1780 $diffall = join( "\n", @diffpreamble );
1781 # add visible labels
1782 if ( defined($visiblelabel) ) {
1783 # Give information right after \begin{document} (or at the beginning of the text for files without preamble
1784 ### if \date command is used, add information to \date argument, otherwise give right after \begin{document}
1785 ### $diffall=~s/(\\date$extraspace(?:\[$brat0\])?$extraspace)\{($pat_n)\}/$1\{$2 \\ LATEXDIFF comparison \\ Old: $oldlabel \\ New: $newlabel \}/ or
1786 $diffbo = "\\begin{verbatim}LATEXDIFF comparison\nOld: $oldlabel\nNew: $newlabel\\end{verbatim}\n$diffbo";
1787 }
1788
1789 $diffall .= "$diffbo";
1790 if ( defined $packages{"hyperref"} && $nolinks ) {
1791 $diffall .= "\\end{NoHyper}\n";
1792 }
1793 $diffall .= "\\end{document}$newpost" if length $newpreamble;
1794 if ( lc($encoding) ne "utf8" && lc($encoding) ne "ascii" ) {
1795 print STDERR "Encoding output file to $encoding\n" if $verbose;
1796 $diffall = Encode::encode( $encoding, $diffall );
1797 binmode STDOUT;
1798 }
1799 print $diffall;
1800
1801
1802 print STDERR "(", exetime(), " s)\n", "Done.\n" if $verbose;
1803
1804 # liststringtoregex(liststring)
1805 # expands string with semi-colon separated list into a regular expression corresponding
1806 # matching any of the elements
1807 sub liststringtoregex {
1808 my ($liststring) = @_;
1809 my @elements = grep /\S/, split( ";", $liststring );
1810 if (@elements) {
1811 return ( '(?:(?:' . join( ')|(?:', @elements ) . '))' );
1812 } else {
1813 return "";
1814 }
1815 }
1816
1817 # show_configuration
1818 # note that this is not encapsulated but uses variables from the main program
1819 # It is provided for convenience because in the future it is planned to allow output
1820 # to be modified based on what packages are read etc - this works only if the input files are actually read
1821 # whether or not additional files are provided
1822 sub show_configuration {
1823 if ($showpreamble) {
1824 print "\n%Preamble commands:\n";
1825 print $latexdiffpreamble ;
1826 }
1827
1828 if ($showsafe) {
1829 print "\nsafecmd: Commands safe within scope of $ADDOPEN $ADDCLOSE and $DELOPEN $DELCLOSE (unless excluded):\n";
1830 print_regex_arr(@SAFECMDLIST);
1831 print "\nsafecmd-exclude: Commands not safe within scope of $ADDOPEN $ADDCLOSE and $DELOPEN $DELCLOSE :\n";
1832 print_regex_arr(@SAFECMDEXCL);
1833 print "\nmboxsafecmd: Commands safe only if they are surrounded by \\mbox command:\n";
1834 print_regex_arr(@MBOXCMDLIST);
1835 print "\nnmboxsafecmd: Commands not safe:\n";
1836 print_regex_arr(@MBOXCMDEXCL);
1837 }
1838
1839 if ($showtext) {
1840 print "\nCommands with last argument textual (unless excluded) and safe in every context:\n";
1841 print_regex_arr(@TEXTCMDLIST);
1842 print
1843 "\nContext1 commands (last argument textual, command will be disabled in deleted passages, last argument will be shown as plain text):\n";
1844 print_regex_arr(@CONTEXT1CMDLIST);
1845 print
1846 "\nContext2 commands (last argument textual, command and its argument will be disabled in deleted passages):\n";
1847 print_regex_arr(@CONTEXT2CMDLIST);
1848 print "\nExclude list of Commands with last argument not textual (overrides patterns above):\n";
1849 print_regex_arr(@TEXTCMDEXCL);
1850 }
1851
1852 if ($showconfig) {
1853 print "Configuration variables:\n";
1854 print "ARRENV=$ARRENV\n";
1855 print "COUNTERCMD=$COUNTERCMD\n";
1856 print "FLOATENV=$FLOATENV\n";
1857 print "ITEMCMD=$ITEMCMD\n";
1858 print "LISTENV=$LISTENV\n";
1859 print "MATHARRENV=$MATHARRENV\n";
1860 # print "MATHARRREPL=$MATHARRREPL\n"; # this is not deprecated and thus no longer shown
1861 print "MATHENV=$MATHENV\n";
1862 print "MATHREPL=$MATHREPL\n";
1863 print "MAXCHANGESLETTER=$MAXCHANGESLETTER\n";
1864 print "MINWORDSBLOCK=$MINWORDSBLOCK\n";
1865 print "PICTUREENV=$PICTUREENV\n";
1866 print "SCALEDELGRAPHICS=$SCALEDELGRAPHICS\n";
1867 print "VERBATIMENV=$VERBATIMENV\n";
1868 print "VERBATIMLINEENV=$VERBATIMLINEENV\n";
1869 print "CUSTOMDIFCMD=$CUSTOMDIFCMD\n";
1870 }
1871 }
1872
1873 ## guess_encoding(filename)
1874 ## reads the first 20 lines of filename and looks for call of inputenc package
1875 ## if found, return the option of this package (encoding), otherwise return utf8
1876 sub guess_encoding {
1877 my ($filename) = @_;
1878 my ( $i, $enc );
1879 open( FH, $filename ) or die("Couldn't open $filename: $!");
1880 $i = 0;
1881 while (<FH>) {
1882 next if /^\s*%/; # skip comment lines
1883 if (m/\\usepackage\[(\w*?)\]\{inputenc\}/) {
1884 close(FH);
1885 return ($1);
1886 }
1887 last if ( ++$i > 20 ); # scan at most 20 non-comment lines
1888 }
1889 close(FH);
1890 ### return("ascii");
1891 return ("utf8");
1892 }
1893
1894 sub read_file_with_encoding {
1895 my ($output);
1896 my ( $filename, $encoding ) = @_;
1897
1898 if ( lc($encoding) eq "utf8" ) {
1899 open( FILE, "<:utf8", $filename ) or die("Couldn't open $filename: $!");
1900 local $/; # locally set record operator to undefined, ie. enable whole-file mode
1901 $output = <FILE>;
1902 } elsif ( lc($encoding) eq "ascii" ) {
1903 open( FILE, $filename ) or die("Couldn't open $filename: $!");
1904 local $/; # locally set record operator to undefined, ie. enable whole-file mode
1905 $output = <FILE>;
1906 } else {
1907 require Encode;
1908 open( FILE, "<", $filename ) or die("Couldn't open $filename: $!");
1909 local $/; # locally set record operator to undefined, ie. enable whole-file mode
1910 $output = <FILE>;
1911 print STDERR "Converting $filename from $encoding to utf8\n" if $verbose;
1912 $output = Encode::decode( $encoding, $output );
1913 }
1914 close FILE;
1915 if ( $^O eq "linux" ) {
1916 $output =~ s/\r\n/\n/g;
1917 }
1918 return $output;
1919 }
1920
1921 ## %packages=list_packages(@preamble)
1922 ## scans the arguments for \documentclass,\RequirePackage and \usepackage statements and constructs a hash
1923 ## whose keys are the included packages, and whose values are the associated optional arguments
1924 #sub list_packages {
1925 # my (@preamble)=@_;
1926 # my %packages=();
1927 # foreach $line ( @preamble ) {
1928 # # get rid of comments
1929 # $line=~s/(?<!\\)%.*$// ;
1930 # if ( $line =~ m/\\(?:documentclass|usepackage|RequirePackage)(?:\[(.+?)\])?\{(.*?)\}/ ) {
1931 ## print STDERR "Found something: |$line|\n" if $debug;
1932 # if (defined($1)) {
1933 # $packages{$2}=$1;
1934 # } else {
1935 # $packages{$2}="";
1936 # }
1937 # }
1938 # }
1939 # return (%packages);
1940 #}
1941
1942 # %packages=list_packages($preamble)
1943 # scans the arguments for \documentclass,\RequirePackage and \usepackage statements and constructs a hash
1944 # whose keys are the included packages, and whose values are the associated optional arguments
1945 # if argument of \usepackage or \RequirePackage is comma separated list, treat as different packages
1946 sub list_packages {
1947 my ($preamble) = @_;
1948 my %packages = ();
1949 my $pkg;
1950
1951 # remove comments
1952 $preamble =~ s/(?<!\\)%.*$//mg;
1953
1954 while ( $preamble =~ m/\\(?:documentclass|usepackage|RequirePackage)(?:\[($brat_n)\])?\{(.*?)\}/gs ) {
1955 if ( defined($1) ) {
1956 foreach $pkg ( split /,/, $2 ) {
1957 $packages{$pkg} = $1;
1958 }
1959 } else {
1960 foreach $pkg ( split /,/, $2 ) {
1961 $packages{$pkg} = "";
1962 }
1963 }
1964 }
1965
1966 # sometimes, class options are defined in such a way that they imply the loading and/or presence of a package
1967 # so we also treat all class options as 'packages.
1968 if ( $preamble =~ m/\\documentclass\s*\[($brat_n)\]\s*\{.*?\}/s ) {
1969 foreach $pkg ( split /,/, $1 ) {
1970 $pkg =~ s/\s//g; # remove space and newline characters
1971 $packages{$pkg} = "" unless exists( $packages{$pkg} );
1972 }
1973 }
1974 return (%packages);
1975 }
1976
1977 # Subroutine add_safe_commands modified from version provided by S. Gouezel
1978 # add_safe_commands($preamble)
1979 # scans the argument for \newcommand and \DeclareMathOperator,
1980 # and adds the created commands which are clearly safe to @SAFECMDLIST
1981 sub add_safe_commands {
1982 my ($preamble) = @_;
1983
1984 # get rid of comments
1985 $preamble =~ s/(?<!\\)%.*$//mg;
1986
1987 my $to_test = "";
1988 # test for \DeclareMathOperator{\foo}{myoperator}
1989 while ( $preamble =~ m/\DeclareMathOperator\s*\*?\{\\(\w*?)\}/osg ) {
1990 $to_test = $1;
1991 if ( $to_test ne ""
1992 and not iscmd( $to_test, \@SAFECMDLIST, \@SAFECMDEXCL )
1993 and not iscmd( $to_test, \@SAFECMDEXCL, [] ) )
1994 {
1995 # one should add $to_test to the list of safe commands.
1996 init_regex_arr_list( \@SAFECMDLIST, $to_test );
1997 print STDERR "Adding $to_test to the list of safe commands\n" if $verbose;
1998 }
1999 }
2000
2001 while ( $preamble =~ m/\\(?:new|renew|provide)command\s*{\\(\w*)\}(?:|\[\d*\])\s*\{(${pat_n})\}/osg ) {
2002 my $maybe_to_test = $1;
2003 my $should_be_safe = $2;
2004 print STDERR "DEBUG Checking new command: maybe_to_test, should_be_safe: $1 $2\n" if $debug;
2005 my $success = 0;
2006 # skip custom diff commands
2007 next if ( $maybe_to_test =~ m/^(?:ADD|DEL)?${CUSTOMDIFCMD}$/ );
2008 ###print STDERR "DEBUG: really test it. \n";
2009 # test if all latex commands inside it are safe
2010 $success = 1;
2011 if ( $should_be_safe =~ m/\\\\/ ) {
2012 $success = 0;
2013 } else {
2014 while ( $should_be_safe =~ m/\\(\w+)/g ) {
2015 ### print STDERR "DEBUG: Testing command $1 " if $debug;
2016 $success = 0 unless iscmd( $1, \@SAFECMDLIST, \@SAFECMDEXCL ); ### or $1 eq "";
2017 ### print STDERR " success=$success\n" if $debug;
2018 }
2019 }
2020 ### }
2021 if ($success) {
2022 $to_test = $maybe_to_test;
2023 if ( not iscmd( $to_test, \@SAFECMDLIST, \@SAFECMDEXCL ) and not iscmd( $to_test, \@SAFECMDEXCL, [] ) ) {
2024 # # one should add $to_test to the list of safe commands.
2025 init_regex_arr_list( \@SAFECMDLIST, $to_test );
2026 print STDERR "Adding $to_test to the list of safe commands\n" if $verbose;
2027 }
2028 }
2029 }
2030 }
2031
2032 # helper function for flatten
2033 # remove \endinput at beginning of line and everything
2034 # following it.
2035 # If \endinput is not at the beginning of
2036 # the line, nothing will be removed. It is assumed that
2037 # this case is most common when \endinput is part of a
2038 # conditional clause. The file will only be processed
2039 # correctly if the conditional is always false,
2040 # i.e. \endinput # not actually reached
2041 sub remove_endinput {
2042 # s/// operates on default input
2043 $_[0] =~ s/^\\endinput.*\Z//ms;
2044 return ( $_[0] );
2045 }
2046
2047 # flatten($text,$preamble,$filename,$encoding)
2048 # expands \input and \include commands within text
2049 # expands \bibliography command with corresponding bbl file if available
2050 # expands \subfile command (from subfiles package - not part of standard text distribution)
2051 # expands \import etc commands (from import package - not part of standard text distribution)
2052 # preamble is scanned for includeonly commands
2053 # encoding is the encoding
2054 # Does not expand codes if they are in the argument of verbatim commands \verb or \listinline
2055
2056 sub flatten {
2057 my ( $text, $preamble, $filename, $encoding ) = @_;
2058 my (
2059 $includeonly, $dirname, $fname, $newpage, $fullfile, $filecontent, $replacement, $begline,
2060 $inputcmd, $bblfile, $subfile, $command, $verbenv, $verboptions, $ignore, $fileonly
2061 );
2062 my ( $subpreamble, $subbody, $subpost );
2063 my ( $subdir, $subdirfull, $importfilepath );
2064 my %verbhash; # shadows global %verbhash - here it is used only within flatten
2065 require File::Basename;
2066 ### require File::Spec ; # now this is needed even if flatten option not given
2067 $filename = File::Spec->rel2abs($filename);
2068 ( $ignore, $dirname, $fileonly ) = File::Spec->splitpath($filename);
2069 $bblfile = $filename;
2070 $bblfile =~ s/\.tex$//;
2071 $bblfile .= ".bbl";
2072
2073 if ( ($includeonly) = ( $preamble =~ m/\\includeonly\{(.*?)\}/ ) ) {
2074 $includeonly =~ s/,/|/g;
2075 } else {
2076 $includeonly = '.*?';
2077 }
2078
2079 #print STDERR "DEBUG: VERBATIMENV |$VERBATIMENV| VERBATIMLINEENV |$VERBATIMLINEENV|\n";
2080 print STDERR "DEBUG: includeonly $includeonly\n" if $debug;
2081
2082 # Run through filter, to let filterscript have a pass if it was set
2083 $text = filter($text);
2084
2085 #turn verbatim environments into hashes
2086 $text =~
2087 s/^((?:[^%\n]|\\%)*)\\begin\{($VERBATIMENV|$VERBATIMLINEENV)\}(.*?)\\end\{\2\}/"${1}\\DIF${2}{". tohash(\%verbhash,"${3}") . "}"/esgm;
2088
2089 #turn verbatim commands into hashes (but not if they are themselves in comments)
2090 $text =~
2091 s/^((?:[^%\n]|\\%)*)\\lstinline((?:\[$brat_n\])?)(\{(?:.*?)\})/"${1}\\DIFlstinline". $2 ."{". tohash(\%verbhash,"${3}") ."}"/esgm;
2092 $text =~
2093 s/^((?:[^%\n]|\\%)*)\\lstinline((?:\[$brat_n\])?)(([^\s\w]).*?\4)/"${1}\\DIFlstinline". $2 ."{". tohash(\%verbhash,"${3}") ."}"/esgm;
2094 ### $text =~ s/\\(verb\*?|lstinline)([^\s\w])(.*?)\2/"\\DIF${1}{". tohash(\%verbhash,"${2}${3}${2}") ."}"/esg;
2095 $text =~
2096 s/^((?:[^\n%]|\\%)*)\\(verb\*?|lstinline)([^\s\w])(.*?)\3/"${1}\\DIF${2}{". tohash(\%verbhash,"${3}${4}${3}") ."}"/esgm;
2097
2098 # Recursively replace \\import, \\subimport, and related import commands
2099 $text =~ s/(^(?:[^%\n]|\\%)*)(\\(sub)?(?:import|inputfrom|includefrom))\{(.*?)\}(?:[\s]*)\{(.*?)\}/{
2100 # (--------1-------)(--(=3=)-------------2-------------------) (-4-) (-5-)
2101 # $1 is begline
2102 # $2 is the import macro name
2103 # $3 is (optional) prefix "sub"
2104 # $4 is directory
2105 # $5 is filename
2106 $begline = (defined($1)? $1 : "");
2107 $subdir = $4;
2108 $fname = $5;
2109 $fname .= ".tex" unless $fname =~ m|\.\w{3,4}$|;
2110 print STDERR "DEBUG begline:", $begline, "\n" if $debug;
2111 print STDERR "DEBUG", (defined($3)? "subimport_file:" : "import_file:"), $subdir, "\n" if $debug;
2112 print STDERR "DEBUG file:", $fname, "\n" if $debug;
2113
2114 # subimport appends $subdir to the current $dirname. import replaces it with an absolute path.
2115 $subdirfull = (defined($3) ? File::Spec->catdir($dirname,$subdir) : $subdir);
2116
2117 $importfilepath = File::Spec->catfile($subdirfull, $fname);
2118
2119 print STDERR "importing importfilepath:", $importfilepath,"\n" if $verbose;
2120 if ( -f $importfilepath ) {
2121 # If file exists, replace input or include command with expanded input
2122 #TODO: need remove_endinput & newpage similar to other replacements inside flatten
2123 $replacement=flatten(read_file_with_encoding($importfilepath, $encoding), $preamble,$importfilepath,$encoding);
2124 } else {
2125 # if file does not exist, do not expand include or input command (do not warn if fname contains #[0-9] as it is then likely part of a command definition
2126 # and is not meant to be expanded directly
2127 print STDERR "WARNING: Could not find included file ",$importfilepath,". I will continue but not expand |$2|\n";
2128 $replacement = $2;
2129 $replacement .= "{$subdir}{$fname} % Processed";
2130 }
2131 "$begline$replacement";
2132 }/exgm;
2133
2134 # recursively replace \\input and \\include files
2135 $text =~ s/(^(?:[^%\n]|\\%)*)(\\input\{(.*?)\}|\\include\{(${includeonly}(?:\.tex)?)\})/{
2136 $begline=(defined($1)? $1 : "") ;
2137 $inputcmd=$2;
2138 $fname = $3 if defined($3) ;
2139 $fname = $4 if defined($4) ;
2140 $newpage=(defined($4)? " \\newpage " : "") ;
2141 # # add tex extension unless there is a three or four letter extension already
2142 $fname .= ".tex" unless $fname =~ m|\.\w{3,4}$|;
2143 $fullfile = File::Spec->catfile($dirname,$fname);
2144 print STDERR "DEBUG Beg of line match |$1|\n" if defined($1) && $debug ;
2145 print STDERR "Include file $fname\n" if $verbose;
2146 print STDERR "DEBUG looking for file ",$fullfile, "\n" if $debug;
2147 # content of file becomes replacement value (use recursion), add \newpage if the command was include
2148 if ( -f $fullfile ) {
2149 # If file exists, replace input or include command with expanded input
2150 $replacement=flatten(read_file_with_encoding($fullfile, $encoding), $preamble,$filename,$encoding);
2151 $replacement = remove_endinput($replacement);
2152 # \include always starts a new page; use explicit \newpage command to simulate this
2153 } else {
2154 # if file does not exist, do not expand include or input command (do not warn if fname contains #[0-9] as it is then likely part of a command definition
2155 # and is not meant to be expanded directly
2156 print STDERR "WARNING: Could not find included file ",$fullfile,". I will continue but not expand |$inputcmd|\n" unless $fname =~ m(#[0-9]) ;
2157 $replacement = $inputcmd ; # i.e. just the original command again -> make no change file does not exist
2158 $newpage="";
2159 }
2160 "$begline$newpage$replacement$newpage";
2161 }/exgm;
2162
2163 # replace bibliography with bbl file if it exists
2164 $text =~ s/(^(?:[^%\n]|\\%)*)\\bibliography\{(.*?)\}/{
2165 if ( -f $bblfile ){
2166 $replacement=read_file_with_encoding(File::Spec->catfile($bblfile), $encoding);
2167 } else {
2168 warn "Bibliography file $bblfile cannot be found. No flattening of \\bibliography done. Run bibtex on old and new files first";
2169 $replacement="\\bibliography{$2}";
2170 }
2171 $begline=(defined($1)? $1 : "") ;
2172 "$begline$replacement";
2173 }/exgm;
2174
2175 # replace subfile with contents (subfile package)
2176 $text =~ s/(^(?:[^%\n]|\\%)*)\\subfile\{(.*?)\}/{
2177 $begline=(defined($1)? $1 : "") ;
2178 $fname = $2;
2179 # # add tex extension unless there is a three or four letter extension already
2180 $fname .= ".tex" unless $fname =~ m|\.\w{3,4}|;
2181 print STDERR "Include file as subfile $fname\n" if $verbose;
2182 # content of file becomes replacement value (use recursion)
2183 # now strip away everything outside and including \begin{document} and \end{document} pair#
2184 # # note: no checking for comments is made
2185 $fullfile=File::Spec->catfile($dirname,$fname);
2186 if ( -f $fullfile) {
2187 # if file exists, expand \subfile command by contents of file
2188 $subfile=read_file_with_encoding($fullfile,$encoding) or die "Could not open included subfile ",$fullfile,": $!";
2189 ($subpreamble,$subbody,$subpost)=splitdoc($subfile,'\\\\begin\{document\}','\\\\end\{document\}');
2190 ### $subfile=~s|^.*\\begin{document}||s;
2191 ### $subfile=~s|\\end{document}.*$||s;
2192 $replacement=flatten($subbody, $preamble,$fullfile,$encoding);
2193 ### $replacement = remove_endinput($replacement);
2194 } else {
2195 # if file does not exist, do not expand subfile
2196 print STDERR "WARNING: Could not find subfile ",$fullfile,". I will continue but not expand |$2|\n" unless $fname =~ m(#[0-9]) ;
2197 $replacement = "\\subfile\{$2\}" ; # i.e. just the original command again -> make no change file does not exist
2198 }
2199
2200 "$begline$replacement";
2201 }/exgm;
2202
2203 # replace \verbatiminput and \lstlistinginput
2204 $text =~ s/(^(?:[^%\n]|\\%)*)\\(verbatiminput\*?|lstinputlisting)$extraspace(\[$brat_n\])?$extraspace\{(.*?)\}/{
2205 $begline=(defined($1)? $1 : "") ;
2206 $command = $2 ;
2207 $fname = $4 ;
2208 $verboptions = defined($3)? $3 : "" ;
2209 if ($command eq 'verbatiminput' ) {
2210 $verbenv = "verbatim" ;
2211 } elsif ($command eq 'verbatiminput*' ) {
2212 $verbenv = "verbatim*" ;
2213 } elsif ($command eq 'lstinputlisting' ) {
2214 $verbenv = "lstlisting" ;
2215 } else {
2216 die "Internal errorL Unexpected verbatim input type $command.\n";
2217 }
2218 print STDERR "DEBUG Beg of line match |$begline|\n" if $debug ;
2219 print STDERR "Include file $fname verbatim\n" if $verbose;
2220 print STDERR "DEBUG looking for file ",File::Spec->catfile($dirname,$fname), "\n" if $debug;
2221 # content of file becomes replacement value (do not use recursion), add \newpage if the command was include
2222 ###$replacement=read_file_with_encoding(File::Spec->catfile($dirname,$fname), $encoding) or die "Couldn't find file ",File::Spec->catfile($dirname,$fname),": $!";
2223 $replacement=read_file_with_encoding(File::Spec->catfile($dirname,$fname), $encoding); # (cannot on apparent failure as this triggers for empty fie. Original: or die "Couldn't find file ",File::Spec->catfile($dirname,$fname),": $!";
2224 # Add a new line if it not already there (note that the matching operator needs to use different delimiters, as we are still inside an outer scope that takes precedence
2225 $replacement .= "\n" unless $replacement =~ m(\n$) ;
2226 "$begline\\begin{$verbenv}$verboptions\n$replacement\\end{$verbenv}\n";
2227 }/exgm;
2228
2229 # recover original text from hashed verbatim commands
2230 $text =~ s/\\DIF((?:verb\*?|lstinline(?:\[$brat_n\])?))\{([-\d]*?)\}/"\\${1}". fromhash(\%verbhash,${2})/esg;
2231 # recover original text from hashed verbatim environments
2232 $text =~
2233 s/\\DIF((?:$VERBATIMENV|$VERBATIMLINEENV)(?:\[$brat_n\])?)\{([-\d]*?)\}/"\\begin{${1}}".fromhash(\%verbhash,$2)."\\end{${1}}"/esg;
2234 ###print STDERR $text . "THE END";
2235 return ($text);
2236 }
2237
2238 # print_regex_arr(@arr)
2239 # prints regex array without x-ism expansion put in by pearl to stdout
2240 sub print_regex_arr {
2241 my $dumstring;
2242
2243 $dumstring = "";
2244 foreach (@_) {
2245 s/\(\?\^u?:\^(.*?)\$\)/$1/g;
2246 next unless /[a-z]/;
2247 $dumstring .= "$_ ";
2248 }
2249 $dumstring = join( " ", @_ ); # PERL generates string (?-xism:^ref$) for quoted refex ^ref$
2250 #$dumstring =~ s/\(\?-xism:\^(.*?)\$\)/$1/g; # remove string and ^,$ marks before output
2251 #$dumstring =~ s/\(\^\?u:\^(.*?)\$\)/$1/g; # remove string and ^,$ marks before output
2252 #(?^u:^title$)
2253 #$dumstring =~ s/\(\?\^u:\^(.*?)\$\)/$1/g; # remove string and ^,$ marks before output
2254 print $dumstring, "\n";
2255 }
2256
2257 # @lines=extrapream($type,...)
2258 # reads line from appendix or external file
2259 # (end of file after __END__ token)
2260 # if $type is a filename, it will read the file instead of reading from the appendix
2261 # otherwise it will screen appendix for line "%DIF $TYPE" and copy everything up to line
2262 # '%DIF END $TYPE' (where $TYPE is upcased version of $type)
2263 # extrapream('-nofail',$type) will---instead of failing---simply return nothing if
2264 # it does not find the matching line in appendix (do not use -nofail option with multiple types!)
2265 sub extrapream {
2266 my @types = @_;
2267 my ( $type, $arg );
2268 my $nofail = 0;
2269 ###my @retval=("%DIF PREAMBLE EXTENSION ADDED BY LATEXDIFF") ;
2270 my @retval = ();
2271 my ($copy);
2272
2273 foreach $arg (@types) {
2274 if ( $arg eq '-nofail' ) {
2275 $nofail = 1;
2276 next;
2277 }
2278 $type = $arg;
2279 $copy = 0;
2280 if ( -f $type || lc $type eq '/dev/null' ) {
2281 print STDERR "Reading preamble file $type\n" if $verbose;
2282 open( FILE, $type ) or die "Cannot open preamble file $type: $!";
2283 if ( defined($encoding) ) {
2284 binmode( FILE, ":encoding($encoding)" );
2285 } else {
2286 require Encode::Locale;
2287 binmode( FILE, ":encoding(locale)" );
2288 }
2289 while (<FILE>) {
2290 chomp;
2291 if ( $_ =~ m/%DIF PREAMBLE/ ) {
2292 push( @retval, "$_" );
2293 } else {
2294 push( @retval, "$_ %DIF PREAMBLE" );
2295 }
2296 }
2297 } else { # not (-f $type)
2298 $type = uc($type); # upcase argument
2299 print STDERR "Preamble Internal Type $type\n" if $verbose;
2300 # save filehandle position (before first read this points to line after __END__)
2301 # but seek DATA,0,0 resets it to the beginning of the file
2302 # see https://stackoverflow.com/questions/4459601/how-can-i-use-data-twice
2303 my $data_start = tell DATA;
2304 while (<DATA>) {
2305 if (m/^%DIF $type/) {
2306 $copy = 1;
2307 } elsif (m/^%DIF END $type/) {
2308 last;
2309 }
2310 chomp;
2311 push( @retval, "$_ %DIF PREAMBLE" ) if $copy;
2312 }
2313 if ( $copy == 0 ) {
2314 unless ($nofail) {
2315 print STDERR "\nPreamble style $type not implemented.\n";
2316 print STDERR "Write latexdiff -h to get help with available styles\n";
2317 exit(2);
2318 }
2319 }
2320 seek DATA, $data_start, 0; # rewind DATA handle to beginning of data record
2321 }
2322 }
2323 ###push (@retval,"%DIF END PREAMBLE EXTENSION ADDED BY LATEXDIFF") ;
2324 return @retval;
2325 }
2326
2327 # ($part1,$part2,$part3)=splitdoc($text,$word1,$word2)
2328 # splits $text into 3 parts at $word1 and $word2.
2329 # if neither $word1 nor $word2 exist, $part1 and $part3 are empty, $part2 is $text
2330 # If only $word1 or $word2 exist but not the other, output an error message.
2331
2332 # NB this version avoids $` and $' for performance reason although it only makes a tiny difference
2333 # (in one test gain a tenth of a second for a 30s run)
2334 sub splitdoc {
2335 my ( $text, $word1, $word2 ) = @_;
2336 my ( $part1, $part2, $part3 ) = ( "", "", "" );
2337 my ( $rest, $pos );
2338
2339 if ( $text =~ m/(^[^%]*)($word1)/mg ) {
2340 $pos = pos $text;
2341 $part1 = substr( $text, 0, $pos - length($2) );
2342 $rest = substr( $text, $pos );
2343 if ( $rest =~ m/(^[^%]*)($word2)/mg ) {
2344 $pos = pos $rest;
2345 $part2 = substr( $rest, 0, $pos - length($2) );
2346 $part3 = substr( $rest, $pos );
2347 } else {
2348 die "$word1 and $word2 not in the correct order or not present as a pair.";
2349 }
2350 } else {
2351 $part2 = $text;
2352 die "$word2 present but not $word1." if ( $text =~ m/(^[^%]*)$word2/ms );
2353 }
2354 return ( $part1, $part2, $part3 );
2355 }
2356
2357
2358
2359
2360
2361 # bodydiff($old,$new)
2362 sub bodydiff {
2363 my ( $oldwords, $newwords ) = @_;
2364 my @retwords;
2365
2366 print STDERR "(", exetime(), " s)\n", "Splitting into latex tokens \n" if $verbose;
2367 print STDERR "Parsing $oldfile \n" if $verbose;
2368 my @oldwords = splitlatex($oldwords);
2369 print STDERR "Parsing $newfile \n" if $verbose;
2370 my @newwords = splitlatex($newwords);
2371
2372 if ($debug) {
2373 open( TOKENOLD, ">", "latexdiff.debug.tokenold" );
2374 print TOKENOLD join( "***\n", @oldwords );
2375 close(TOKENOLD);
2376 open( TOKENNEW, ">", "latexdiff.debug.tokennew" );
2377 print TOKENNEW join( "***\n", @newwords );
2378 close(TOKENNEW);
2379 }
2380
2381 print STDERR "(", exetime(), " s)\n",
2382 "Pass 1: Expanding text commands and merging isolated identities with changed blocks "
2383 if $verbose;
2384 pass1( \@oldwords, \@newwords );
2385
2386 ### print STDERR "(",exetime()," s)\n","tokenizeblocks: " if $verbose;
2387
2388 print STDERR "(", exetime(), " s)\n", "Pass 2: inserting DIF tokens and mark up. " if $verbose;
2389 # make blocks enclosed by %BEGIN|END DIFFadd|DIFdel into a single token (for markup they will be split again in marktags() )
2390 tokenizeblocks( \@oldwords, "DIFDEL" );
2391 tokenizeblocks( \@newwords, "DIFADD" );
2392 if ($debug) {
2393 open( TOKENOLD, ">", "latexdiff.debug.tokenold2" );
2394 print TOKENOLD join( "***\n", @oldwords );
2395 close(TOKENOLD);
2396 open( TOKENNEW, ">", "latexdiff.debug.tokennew2" );
2397 print TOKENNEW join( "***\n", @newwords );
2398 close(TOKENNEW);
2399 }
2400
2401 @retwords = pass2( \@oldwords, \@newwords );
2402
2403 return (@retwords);
2404 }
2405
2406 # @words=splitlatex($string)
2407 # split string according to latex rules
2408 # Each element of words is either
2409 # a word (including trailing spaces and punctuation)
2410 # a latex command
2411 # if there is white space in the beginning return that as first token
2412 sub splitlatex {
2413 my ($inputstring) = @_;
2414 my $string = $inputstring;
2415 # if input is empty, return empty list
2416 length($string) > 0 or return ();
2417 $string =~ s/^(\s*)//s;
2418 my $leadin = $1;
2419 length($string) > 0 or return ($leadin);
2420
2421 my @retval = ( $string =~ m/$pat/osg );
2422
2423 if ( length($string) != length( join( "", @retval ) ) ) {
2424 print STDERR
2425 "\nWARNING: Inconsistency in length of input string and parsed string:\n This often indicates faulty or non-standard latex code.\n In many cases you can ignore this and the following warning messages.\n Note that character numbers in the following are counted beginning after \\begin{document} and are only approximate."
2426 unless $ignorewarnings;
2427 print STDERR "DEBUG Original length ", length($string), " Parsed length ", length( join( "", @retval ) ), "\n"
2428 if $debug;
2429 print STDERR "DEBUG Input string: |$string|\n" if ( length($string) < 500 ) && $debug;
2430 print STDERR "DEBUG Token parsing: |", join( "+", @retval ), "|\n" if ( length($string) < 500 ) && $debug;
2431 @retval = ();
2432 # slow way only do this if other m//sg method fails
2433 my $last = 0;
2434 while ( $string =~ m/$pat/osg ) {
2435 my $match = $&;
2436 if ( $last + length $& != pos $string ) {
2437 my $pos = pos($string);
2438 my $offset = 30 < $last ? 30 : $last;
2439 my $dum = substr( $string, $last - $offset, $pos - $last + 2 * $offset );
2440 my $dum1 = $dum;
2441 my $cnt = $#retval;
2442 my $i;
2443 $dum1 =~ s/\n/ /g;
2444 unless ($ignorewarnings) {
2445 print STDERR "\n$dum1\n";
2446 print STDERR " " x 30, "^" x ( $pos - $last ), " " x 30, "\n";
2447 print STDERR "Missing characters near word "
2448 . ( scalar @retval )
2449 . " character index: "
2450 . $last . "-"
2451 . pos($string)
2452 . " Length: "
2453 . length($match)
2454 . " Match: |$match| (expected match marked above).\n";
2455 }
2456 # put in missing characters `by hand'
2457 push( @retval, substr( $dum, $offset, $pos - $last - length($match) ) );
2458 # Note: there seems to be a bug in substr with utf8 that made the following line output substr which were too long,
2459 # using dum instead appears to work
2460 # push (@retval, substr($string,$last, pos($string)-$last-length($match)));
2461 }
2462 push( @retval, $match );
2463 $last = pos $string;
2464 }
2465
2466 }
2467
2468 unshift( @retval, $leadin ) if ( length($leadin) > 0 );
2469 return @retval;
2470 }
2471
2472 # pass1( \@seq1,\@seq2)
2473 # Look for differences between seq1 and seq2.
2474 # Where an common-subsequence block is flanked by deleted or appended blocks,
2475 # and is shorter than $MINWORDSBLOCK words it is appended
2476 # to the last deleted or appended word. If the block contains tokens other than words
2477 # or punctuation it is not merged.
2478 # Deleted or appended block consisting of words and safe commands only are
2479 # also merged, to prevent break-up in pass2 (after previous isolated words have been removed)
2480 # If there are commands with textual arguments (e.g. \caption) both in corresponding
2481 # appended and deleted blocks split them such that the command and opening bracket
2482 # are one token, then the rest is split up following standard rules, and the closing
2483 # bracket is a separate token, ie. turn
2484 # "\caption{This is a textual argument}" into
2485 # ("\caption{","This ","is ","a ","textual ","argument","}")
2486 # No return value. Destructively changes sequences
2487 sub pass1 {
2488 my $seq1 = shift;
2489 my $seq2 = shift;
2490
2491 my $len1 = scalar @$seq1;
2492 my $len2 = scalar @$seq2;
2493 # Note: I tried to include range 0-9 as acceptable characters, but in 2 cases in the testsuite, this led to
2494 # arguably worse outcomes, and for 3 it was neutral (5 changes in total in 3 files). This is not representative
2495 # but based on this evidence I skip
2496 my $wpat = qr/^(?:[a-zA-Z.,'`:;?()!\/]*)[\s~]*$/; #'
2497
2498 my ( $last1, $last2 ) = ( -1, -1 );
2499 my $cnt = 0;
2500 my $block = [];
2501 my $addblock = [];
2502 my $delblock = [];
2503 my $todo = [];
2504 my $instruction = [];
2505 my $i;
2506 my ( @delmid, @addmid, @dummy );
2507
2508 my ( $addcmds, $delcmds, $matchindex );
2509 my ( $addtextblocks, $deltextblocks );
2510 my ( $addtokcnt, $deltokcnt, $mattokcnt ) = ( 0, 0, 0 );
2511 my ( $addblkcnt, $delblkcnt, $matblkcnt ) = ( 0, 0, 0 );
2512
2513 my $adddiscard = sub {
2514 if ( $cnt > 0 ) {
2515 $matblkcnt++;
2516 # just after an unchanged block
2517 # print STDERR "Unchanged block $cnt, $last1,$last2 \n";
2518 if (
2519 $cnt < $MINWORDSBLOCK
2520 && $cnt == scalar(
2521 grep {
2522 /^$wpat/
2523 || ( /^(?:\\protect)?\\((?:[`'^"~=.]|[\w\d@*]+))((?:\[$brat_n\]|\{$pat_n\})*)/o
2524 && iscmd( $1, \@SAFECMDLIST, \@SAFECMDEXCL )
2525 && scalar( @dummy = split( " ", $2 ) ) < 3 )
2526 } @$block
2527 )
2528 )
2529 {
2530 # merge identical blocks shorter than $MINWORDSBLOCK
2531 # and only containing ordinary words
2532 # with preceding different word
2533 # We cannot carry out this merging immediately as this
2534 # would change the index numbers of seq1 and seq2 and confuse
2535 # the algorithm, instead we store in @$todo where we have to merge
2536 push( @$todo, [ $last1, $last2, $cnt, @$block ] );
2537 }
2538 $block = [];
2539 $cnt = 0;
2540 $last1 = -1;
2541 $last2 = -1;
2542 }
2543 };
2544 my $discard = sub {
2545 $deltokcnt++;
2546 &$adddiscard; #($_[0],$_[1]);
2547 push( @$delblock, [ $seq1->[ $_[0] ], $_[0] ] );
2548 $last1 = $_[0];
2549 };
2550
2551 my $add = sub {
2552 $addtokcnt++;
2553 &$adddiscard; #($_[0],$_[1]);
2554 push( @$addblock, [ $seq2->[ $_[1] ], $_[1] ] );
2555 $last2 = $_[1];
2556 };
2557
2558 my $match = sub {
2559 $mattokcnt++;
2560 if ( $cnt == 0 ) { # first word of matching sequence after changed sequence or at beginning of word sequence
2561 $deltextblocks = extracttextblocks($delblock);
2562 $delblkcnt++ if scalar @$delblock;
2563 $addtextblocks = extracttextblocks($addblock);
2564 $addblkcnt++ if scalar @$addblock;
2565
2566 # make a list of all TEXTCMDLIST commands in deleted and added blocks
2567 $delcmds = extractcommands($delblock);
2568 $addcmds = extractcommands($addblock);
2569 # now find those text commands, which are found in both deleted and added blocks, and expand them
2570 # keygen(third argument of _longestCommonSubsequence) implies to sort on command (0th elements of $addcmd elements)
2571 # the calling format for longestCommonSubsequence has changed between versions of
2572 # Algorithm::Diff so we need to check which one we are using
2573 if ( $algodiffversion > 1.15 ) {
2574 ### Algorithm::Diff 1.19
2575 $matchindex = Algorithm::Diff::_longestCommonSubsequence( $delcmds, $addcmds, 0, sub { $_[0]->[0] } );
2576 } else {
2577 ### Algorithm::Diff 1.15
2578 $matchindex = Algorithm::Diff::_longestCommonSubsequence( $delcmds, $addcmds, sub { $_[0]->[0] } );
2579 }
2580
2581 for ( $i = 0 ; $i <= $#$matchindex ; $i++ ) {
2582 if ( defined( $matchindex->[$i] ) ) {
2583 $j = $matchindex->[$i];
2584 @delmid = splitlatex( $delcmds->[$i][3] );
2585 @addmid = splitlatex( $addcmds->[$j][3] );
2586 while ( scalar(@$deltextblocks) && $deltextblocks->[0][0] < $delcmds->[$i][1] ) {
2587 my ( $index, $block, $cnt ) = @{ shift(@$deltextblocks) };
2588 push( @$todo, [ $index, -1, $cnt, @$block ] );
2589 }
2590 push( @$todo, [ $delcmds->[$i][1], -1, -1, $delcmds->[$i][2], @delmid, $delcmds->[$i][4] ] );
2591
2592 while ( scalar(@$addtextblocks) && $addtextblocks->[0][0] < $addcmds->[$j][1] ) {
2593 my ( $index, $block, $cnt ) = @{ shift(@$addtextblocks) };
2594 push( @$todo, [ -1, $index, $cnt, @$block ] );
2595 }
2596 push( @$todo, [ -1, $addcmds->[$j][1], -1, $addcmds->[$j][2], @addmid, $addcmds->[$j][4] ] );
2597 }
2598 }
2599 # mop up remaining textblocks
2600 while ( scalar(@$deltextblocks) ) {
2601 my ( $index, $block, $cnt ) = @{ shift(@$deltextblocks) };
2602 push( @$todo, [ $index, -1, $cnt, @$block ] );
2603 }
2604 while ( scalar(@$addtextblocks) ) {
2605 my ( $index, $block, $cnt ) = @{ shift(@$addtextblocks) };
2606 push( @$todo, [ -1, $index, $cnt, @$block ] );
2607 }
2608
2609 $addblock = [];
2610 $delblock = [];
2611 }
2612 push( @$block, $seq2->[ $_[1] ] );
2613 $cnt++;
2614 };
2615
2616 my $keyfunc = sub { join( " ", split( " ", shift() ) ) };
2617
2618 traverse_sequences( $seq1, $seq2, { MATCH => $match, DISCARD_A => $discard, DISCARD_B => $add }, $keyfunc );
2619
2620 # now carry out the merging/splitting. Refer to elements relative from
2621 # the end (with negative indices) as these offsets don't change before the instruction is executed
2622 # cnt>0: merged small unchanged groups with previous changed blocks
2623 # cnt==-1: split textual commands into components
2624 foreach $instruction (@$todo) {
2625 ( $last1, $last2, $cnt, @$block ) = @$instruction;
2626 if ( $cnt >= 0 ) {
2627 splice( @$seq1, $last1 - $len1, 1 + $cnt, join( "", $seq1->[ $last1 - $len1 ], @$block ) ) if $last1 >= 0;
2628 splice( @$seq2, $last2 - $len2, 1 + $cnt, join( "", $seq2->[ $last2 - $len2 ], @$block ) ) if $last2 >= 0;
2629 } else {
2630 splice( @$seq1, $last1 - $len1, 1, @$block ) if $last1 >= 0;
2631 splice( @$seq2, $last2 - $len2, 1, @$block ) if $last2 >= 0;
2632 }
2633 }
2634
2635 if ($debug) {
2636 print STDERR "\n";
2637 print STDERR " $mattokcnt matching tokens in $matblkcnt blocks.\n";
2638 print STDERR " $deltokcnt discarded tokens in $delblkcnt blocks.\n";
2639 print STDERR " $addtokcnt appended tokens in $addblkcnt blocks.\n";
2640 }
2641 }
2642
2643 # extracttextblocks(\@blockindex)
2644 # $blockindex has the following format
2645 # [ [ token1, index1 ], [token2, index2],.. ]
2646 # where index refers to the index in the original old or new word sequence
2647 # Returns: reference to an array of the form
2648 # [[ $index, $textblock, $cnt ], ..
2649 # where $index index of block to be merged
2650 # $textblock contains all the words to be merged with the word at $index (but does not contain this word)
2651 # $cnt is length of block
2652 #
2653 # requires: iscmd
2654 #
2655 sub extracttextblocks {
2656 my $block = shift;
2657 my ( $i, $token, $index );
2658 my $textblock = [];
2659 my $last = -1;
2660 my $wpat = qr/^(?:[a-zA-Z.,'`:;?()!]*)[\s~]*$/; #'
2661 my $retval = [];
2662
2663 # we redefine locally $extraspace (shadowing the global definition) to capture command sequences with intervening spaces no matter what the global setting
2664 # this is done so we can capture those commands with a predefined number of arguments without having to introduce them again explicitly here
2665 my $extraspace = '\s*';
2666
2667 for ( $i = 0 ; $i < scalar @$block ; $i++ ) {
2668 ( $token, $index ) = @{ $block->[$i] };
2669 # store pure text blocks
2670 if (
2671 $token =~ /$wpat/
2672 || ( $token =~
2673 /^(?:\\protect)?\\((?:[`'^"~=.]|[\w\d@\*]+))((?:${extraspace}\[$brat_n\]${extraspace}|${extraspace}\{$pat_n\})*)/
2674 && iscmd( $1, \@SAFECMDLIST, \@SAFECMDEXCL )
2675 && !iscmd( $1, \@TEXTCMDLIST, \@TEXTCMDEXCL ) )
2676 )
2677 {
2678 # we have text or a command which can be treated as text
2679 if ( $last < 0 ) {
2680 # new pure-text block
2681 $last = $index;
2682 } else {
2683 # add to pure-text block
2684 push( @$textblock, $token );
2685 }
2686 } else {
2687 # it is not text
2688 if ( scalar(@$textblock) ) {
2689 push( @$retval, [ $last, $textblock, scalar(@$textblock) ] );
2690 }
2691 $textblock = [];
2692 $last = -1;
2693 }
2694 }
2695 # finish processing a possibly unfinished block before returning
2696 if ( scalar(@$textblock) ) {
2697 push( @$retval, [ $last, $textblock, scalar(@$textblock) ] );
2698 }
2699 return ($retval);
2700 }
2701
2702 # extractcommands( \@blockindex )
2703 # $blockindex has the following format
2704 # [ [ token1, index1 ], [token2, index2],.. ]
2705 # where index refers to the index in the original old or new word sequence
2706 # Returns: reference to an array of the form
2707 # [ [ "\cmd1", index, "\cmd1[optarg]{arg1}{", "arg2" ,"} " ],..
2708 # where index is just taken from input array
2709 # command must have a textual argument as last argument
2710 #
2711 # requires: iscmd
2712 #
2713 sub extractcommands {
2714 my $block = shift;
2715 my ( $i, $token, $index, $cmd, $open, $mid, $closing );
2716 my $retval = [];
2717
2718 # we redefine locally $extraspace (shadowing the global definition) to capture command sequences with intervening spaces no matter what the global setting
2719 # this is done so we can capture those commands with a predefined number of arguments without having to introduce them again explicitly here
2720 my $extraspace = '\s*';
2721
2722 for ( $i = 0 ; $i < scalar @$block ; $i++ ) {
2723 ( $token, $index ) = @{ $block->[$i] };
2724 # check if token is an alphanumeric command sequence with at least one non-optional argument
2725 # \cmd[...]{...}{last argument}
2726 # Capturing in the following results in these associations
2727 # $1: \cmd[...]{...}{
2728 # $2: \cmd
2729 # $3: last argument
2730 # $4: } + trailing spaces
2731 if (
2732 (
2733 $token =~
2734 m/^((?:\\protect)?\\([\w\d\*]+)(?:${extraspace}\[$brat_n\]|${extraspace}\{$pat_n\})*${extraspace}\{)($pat_n)(\}\s*)$/so
2735 )
2736 && iscmd( $2, \@TEXTCMDLIST, \@TEXTCMDEXCL )
2737 )
2738 {
2739 print STDERR "DEBUG EXTRACTCOMMANDS Match |$1|$2|$3|$4|$index \n" if $debug;
2740 # push(@$retval,[ $2,$index,$1,$3,$4 ]);
2741 ( $cmd, $open, $mid, $closing ) = ( $2, $1, $3, $4 );
2742 $closing =~ s/\}/\\RIGHTBRACE/;
2743 push( @$retval, [ $cmd, $index, $open, $mid, $closing ] );
2744 }
2745 }
2746 return $retval;
2747 }
2748
2749 # iscmd($cmd,\@regexarray,\@regexexcl) checks
2750 # return 1 if $cmd matches any of the patterns in the
2751 # array $@regexarray, and none of the patterns in \@regexexcl, otherwise return 0
2752 sub iscmd {
2753 my ( $cmd, $regexar, $regexexcl ) = @_;
2754 my ($ret) = 0;
2755 ### print STDERR "DEBUG: iscmd($cmd) in @$regexar, \n---------\n excluding @$regexexcl or @TEXTCMDEXCL safe @SAFECMDEXCL \n" if $debug;
2756 ### print STDERR "DEBUG: iscmd($cmd)=" if $debug;
2757 foreach $pat (@$regexar) {
2758 if ( $cmd =~ m/^${pat}$/ ) {
2759 $ret = 1;
2760 last;
2761 }
2762 }
2763 ### print STDERR "0\n" if ($debug && !$ret) ;
2764 return 0 unless $ret;
2765 foreach $pat (@$regexexcl) {
2766 ### print STDERR "0\n" if ( $debug && $cmd =~ m/^${pat}$/) ;
2767 return 0 if ( $cmd =~ m/^${pat}$/ );
2768 }
2769 ### print STDERR "1\n" if $debug;
2770 return 1;
2771 }
2772
2773 # tokenizeblocks( \@seq, $blocktype)
2774 # destructively turn blocks enclosed by %BEGIN|END $blocktype into a single token for the sequence pointed
2775 # to by \@seq
2776 sub tokenizeblocks {
2777 my ( $seq, $blocktype ) = @_;
2778 my @new_seq = ();
2779 my @accumulate = ();
2780 my ($token);
2781 my @midtokens;
2782 my @matches;
2783 my ( $i, $cmd, $opening, $mid, $closing );
2784 my $mode; # 0: copy mode, 1: accumulate mode (inside block)
2785
2786 $mode = 0;
2787 $i = 0;
2788 while ( $i <= $#$seq ) {
2789 $token = $seq->[$i];
2790 # check if BEGIN/END and block directive is present in the argument of any textcmd. This will be in an
2791 # unchanged block. (textcmds in changed blocks would have already been expanded in pass1)
2792 if ( $token =~
2793 m/^((?:\\protect)?\\([\w\d\*]+)(?:${extraspace}\[$brat_n\]|${extraspace}\{$pat_n\})*${extraspace}\{)($pat_n)(\}?\s*)$/so
2794 )
2795 {
2796 ( $cmd, $opening, $mid, $closing ) = ( $2, $1, $3, $4 );
2797 #print STDERR "DEBUG tokenizeblocks Match $i: |$1|$2|$3|$4|\n";
2798 if ( iscmd( $cmd, \@TEXTCMDLIST, \@TEXTCMDEXCL ) ) {
2799 # command is a text command
2800 if ( $mid =~ m/%(?:BEGIN|END) DIF(?:ADD|DEL|NOMARKUP)/ ) {
2801 # if it contains a directive
2802 # => we expand the interior of the text command and continue processing
2803 @midtokens = splitlatex($mid);
2804 ###print STDERR "DEBUG tokenizeblocks: midtokens $#$seq $#midtokens|\n";
2805 #$closing =~ s/\}/\\RIGHTBRACE/ ;
2806 splice( @$seq, $i, 1, $opening, @midtokens, $closing );
2807 ####print STDERR "DEBUG tokenizeblocks: $#$seq|\n";
2808 next; # the next will cause the freshly expanded tokens to be parsed again
2809 }
2810 }
2811 if ( @matches = ( $token =~ m/(%(?:BEGIN|END) DIF(?:ADD|DEL|NOMARKUP).*)/g ) ) {
2812 # any directive in non-text command or earlier arguments
2813 # neuter the directives, so that they do not appear again in the next iteration
2814 $token =~ s/%BEGIN DIF(ADD|DEL|NOMARKUP)/%begin DIF$1/g;
2815 $token =~ s/%END DIF(ADD|DEL|NOMARKUP)/%end DIF$1/g;
2816 ### print STDERR "DEBUG command : Match $i, ",scalar @matches," |$token|",join("-",@matches),"\n";
2817 if ( scalar @matches > 1 || $matches[0] =~ m/%END/ ) {
2818 splice( @$seq, $i, 0, shift(@matches) . " AUX\n" );
2819 splice( @$seq, $i + 1, 1, $token, map { "$_ AUX\n" } @matches ); # append the directives as separate tokens
2820 } else {
2821 splice( @$seq, $i, 1, $token, map { "$_ AUX\n" } @matches ); # append the directives as separate tokens
2822 }
2823 next;
2824 }
2825 }
2826 $i++;
2827 #foreach $token ( @$seq ) {
2828 if ( $token =~ m/^%BEGIN $blocktype/ ) {
2829 if ( $mode == 1 ) {
2830 print STDERR
2831 "WARNING: Two consecutive %BEGIN $blocktype directive detected. Maybe the preceding %END $blocktype was placed in a command argument and overlooked?\n";
2832 # We assume that this occurs because previous %END $blocktype was overlooked rather than actual nesting
2833 # therefore we append the accumulated tokens as indivual tokens, effectively ignoring the previous BEGIN directive but
2834 # honouring the current one
2835 push( @new_seq, @accumulate );
2836 }
2837 $mode = 1;
2838 @accumulate = ($token);
2839 } elsif ( $token =~ m/^%END $blocktype/ ) {
2840 if ($mode) {
2841 # regular behaviour
2842 $mode = 0;
2843 push( @accumulate, $token );
2844 push( @new_seq, join( "", @accumulate ) ); # append the merged tokens so they appear as a single token
2845 } else {
2846 print STDERR
2847 "WARNING: %END $blocktype directive without preceding BEGIN $blocktype. Maybe the preceding %BEGIN $blocktype was placed in a command argument and overlooked?\n";
2848 # We assume that this occurs because previous %BEGIN $blocktype was overlooked rather than actual nesting
2849 # We have to do nothing here (except add the token to the sequence)
2850 push( @new_seq, $token );
2851 }
2852 } elsif ($mode) {
2853 push( @accumulate, $token );
2854 } else {
2855 push( @new_seq, $token );
2856 }
2857 }
2858 @$seq = @new_seq;
2859 }
2860
2861 # pass2( \@seq1,\@seq2)
2862 # Look for differences between seq1 and seq2.
2863 # Mark begin and end of deleted and appended sequences with tags $DELOPEN and $DELCLOSE
2864 # and $ADDOPEN and $ADDCLOSE, respectively, however exclude { } & and all comands, unless
2865 # they match an element of the whitelist (SAFECMD)
2866 # For words in TEXTCMD but not in SAFECMD, enclose interior with $ADDOPEN and $ADDCLOSE brackets
2867 # Deleted comment lines are marked with %DIF <
2868 # Added comment lines are marked with %DIF >
2869 sub pass2 {
2870 my $seq1 = shift;
2871 my $seq2 = shift;
2872
2873 my ( $addtokcnt, $deltokcnt, $mattokcnt ) = ( 0, 0, 0 );
2874 my ( $addblkcnt, $delblkcnt, $matblkcnt ) = ( 0, 0, 0 );
2875
2876 my $retval = [];
2877 my $delhunk = [];
2878 my $addhunk = [];
2879
2880 # State variable that should be accessible to subroutines
2881 local $suppress_markup = 0; # 0: do not block markup, 1: block markup (supporting DIFNOMARKUP directives)
2882
2883 my $discard = sub {
2884 $deltokcnt++;
2885 push( @$delhunk, $seq1->[ $_[0] ] );
2886 };
2887
2888 my $add = sub {
2889 $addtokcnt++;
2890 push( @$addhunk, $seq2->[ $_[1] ] );
2891 };
2892
2893 my $match = sub {
2894 $mattokcnt++;
2895 if ( scalar @$delhunk ) {
2896 $delblkcnt++;
2897 # mark up changes, but comment out commands
2898 push @$retval,
2899 marktags( $DELMARKOPEN, $DELMARKCLOSE, $DELOPEN, $DELCLOSE, $DELCMDOPEN, $DELCMDCLOSE, $DELCOMMENT, $delhunk );
2900 $delhunk = [];
2901 }
2902 if ( scalar @$addhunk ) {
2903 $addblkcnt++;
2904 # we mark up changes, but simply quote commands
2905 push @$retval, marktags( $ADDMARKOPEN, $ADDMARKCLOSE, $ADDOPEN, $ADDCLOSE, "", "", $ADDCOMMENT, $addhunk );
2906 $addhunk = [];
2907 }
2908 push( @$retval, $seq2->[ $_[1] ] );
2909 # Update DIFNOMARKUP counter
2910 ### # save procedure
2911 ### my $cnt_bnomarkup = scalar(grep { /^%BEGIN DIFNOMARKUP/ } @$retval);
2912 ### my $cnt_enomarkup = scalar(grep { /^%END DIFNOMARKUP/ } @$retval);
2913 ### if ( $cnt_bnomarkup == $cnt_enomarkup+1 && !$suppress_markup ) {
2914 ### $suppress_markup = 1;
2915 ### } elsif ( $cnt_bnomarkup+1 == $cnt_enomarkup && $suppress_markup ) {
2916 ### $suppress_markup = 0;
2917 ### } elsif { $cnt_bnomarkup == $cnt_enomarkup ) {
2918 ### pass; # DIFNOMARKUP directives are paired appropriately
2919 ### } else {
2920 ### print STDERR "WARNING: DIFNOMARKUP nesting incorrect. Using last value to determine next state irrespective of earlier state\n";
2921 # shortcut relying on the last DIFNOMARKUP directive; this relies on proper nesting
2922
2923 my @nomarkups = grep ( /^%(BEGIN|END) DIFNOMARKUP/, $seq2->[ $_[1] ] );
2924
2925 if ( scalar @nomarkups ) {
2926 if ( $nomarkups[-1] =~ /^%BEGIN DIFNOMARKUP/ ) {
2927 $suppress_markup = 1;
2928 } elsif ( $nomarkups[-1] =~ /^%END DIFNOMARKUP/ ) {
2929 $suppress_markup = 0;
2930 }
2931 }
2932 ### }
2933 };
2934
2935 my $keyfunc = sub { join( " ", split( " ", shift() ) ) };
2936
2937 traverse_sequences( $seq1, $seq2, { MATCH => $match, DISCARD_A => $discard, DISCARD_B => $add }, $keyfunc );
2938 # clear up unprocessed hunks
2939 push @$retval,
2940 marktags( $DELMARKOPEN, $DELMARKCLOSE, $DELOPEN, $DELCLOSE, $DELCMDOPEN, $DELCMDCLOSE, $DELCOMMENT, $delhunk )
2941 if scalar @$delhunk;
2942 push @$retval, marktags( $ADDMARKOPEN, $ADDMARKCLOSE, $ADDOPEN, $ADDCLOSE, "", "", $ADDCOMMENT, $addhunk )
2943 if scalar @$addhunk;
2944
2945 if ($debug) {
2946 print STDERR "\n";
2947 print STDERR " $mattokcnt matching tokens. \n";
2948 print STDERR " $deltokcnt discarded tokens in $delblkcnt blocks.\n";
2949 print STDERR " $addtokcnt appended tokens in $addblkcnt blocks.\n";
2950 }
2951 return (@$retval);
2952 }
2953
2954 # marktags($openmark,$closemark,$open,$close,$opencmd,$closecmd,$comment,\@block)
2955 # returns ($openmark,$open,$block,$close,$closemark) if @block contains no commands (except white-listed ones),
2956 # braces, ampersands, or comments
2957 # mark comments with $comment
2958 # exclude all other exceptions from scope of open, close like this
2959 # ($openmark, $open,...,$close, $opencmd,command, command,$closecmd, $open, ..., $close, $closemark)
2960 # If $opencmd begins with "%" marktags assumes it is operating on a deleted block, otherwise on an added block.
2961 # marktags also respects the local variable $suppress_markup, which if set to 1 will block markup; and also
2962 # updates it if encountering DIFNOMARKUP directives
2963 sub marktags {
2964 my ( $openmark, $closemark, $open, $close, $opencmd, $closecmd, $comment, $block ) = @_;
2965 my $word;
2966 my (@argtext);
2967 my $retval = [];
2968 my $noncomment = 0; # flag to indicate whether we have already written a non-comment token
2969 my $cmd = -1; # -1 at beginning 0: last token written is a ordinary word
2970 # 1: last token written is a command
2971 # for keeping track whether we are just in a command sequence or in a word sequence
2972 my $cmdcomment = ( $opencmd =~ m/^%/ ); # Flag to indicate whether opencmd is a comment (i.e. if we intend to simply comment out changed commands). Usually this means we are in a deleted block
2973 my ( $command, $commandword, $closingbracket ); # temporary variables needed below to remember sub-pattern matches
2974 our $suppress_markup; # we need to keep track across function calls, and also modifications outside
2975
2976 # split this block to split sequences joined in pass1, and %BEGIN|END DIFADD|DIFDEL blocks
2977 ### print STDERR "DEBUG: marktags before splitlatex blocksplit ",join("|",@$block),"\n" if $debug;
2978 @$block = splitlatex( join "", @$block );
2979 ### print STDERR "DEBUG: marktags $openmark,$closemark,$open,$close,$opencmd,$closecmd,$comment\n" if $debug;
2980 print STDERR "DEBUG: after splitlatex ", join( "|", @$block ), "\n" if $debug;
2981
2982 # we redefine locally $extraspace (shadowing the global definition) to capture command sequences with intervening spaces no matter what the global setting
2983 # this is done so we can capture those commands with a predefined number of arguments without having to introduce them again explicitly here
2984 my $extraspace_mt = '\s*';
2985
2986 foreach (@$block) {
2987 $word = $_;
2988 ### print STDERR "DEBUG MARKTAGS: |$word| $suppress_markup | $cmdcomment\n" ;
2989 # check for DIFNOMARKUP tags but ignore them in deleted blocks
2990 if ( !$cmdcomment && $word =~ /^%BEGIN DIFNOMARKUP/ ) {
2991 $suppress_markup = 1;
2992 # close any open blocks if needed:
2993 push( @$retval, $close ) if $cmd == 0;
2994 push( @$retval, $closecmd ) if $cmd == 1;
2995 push( @$retval, $closemark ) if ($noncomment);
2996 push( @$retval, $closecmd );
2997
2998 push( @$retval, $word );
2999
3000 # reset state as if at the the beginning of marktags
3001 $cmd = -1;
3002 $noncomment = 0;
3003
3004 next;
3005 }
3006 if ( !$cmdcomment && $word =~ /^%END DIFNOMARKUP/ ) {
3007 $suppress_markup = 0;
3008 push( @$retval, $word );
3009 next;
3010 }
3011 if ($suppress_markup) {
3012 # simply add the words as received without marking up
3013 push( @$retval, $word );
3014 next;
3015 }
3016 if ( $word =~ s/^%/%$comment/ ) {
3017 # a comment
3018 if ( $cmd == 1 ) {
3019 push( @$retval, $closecmd );
3020 $cmd = -1;
3021 }
3022 push( @$retval, $word );
3023 next;
3024 }
3025 if ( $word =~ m/^\s*$/ ) {
3026 ### print STDERR "DEBUG MARKTAGS: whitespace detected |$word| cmdcom |$cmdcomment| |$opencmd|\n" if $debug;
3027 # a sequence of white-space characters - this should only ever happen for the first element of block.
3028 # in deleted block, omit, otherwise just copy it in
3029 if ( !$cmdcomment ) { # ignore in deleted blocks
3030 push( @$retval, $word );
3031 }
3032 next;
3033 }
3034 if ( !$noncomment ) {
3035 push( @$retval, $openmark );
3036 $noncomment = 1;
3037 }
3038 # negative lookahead pattern (?!) in second clause is put in to avoid matching \( .. \) patterns
3039 # also note that second pattern will match \\
3040 if ( $word =~ /^[&{}\[\]]/
3041 || ( $word =~ /^(?:\\protect)?\\(?!\()(\\|[`'^"~=.]|[\w*@]+)/ && !iscmd( $1, \@SAFECMDLIST, \@SAFECMDEXCL ) ) )
3042 {
3043 ### if ( $word =~ /^[&{}\[\]]/ || ( $word =~ /^\\([\w*@\\% ]+)/ && !iscmd($1,\@SAFECMDLIST,\@SAFECMDEXCL)) ) {
3044 # word is a command or other significant token (not in SAFECMDLIST)
3045 ## same conditions as in subroutine extractcommand:
3046 # check if token is an alphanumeric command sequence with at least one non-optional argument
3047 # \cmd[...]{...}{last argument}
3048 # Capturing in the following results in these associations
3049 # $1: \cmd[...]{...}{
3050 # $2: cmd
3051 # $3: last argument
3052 # $4: } + trailing spaces
3053 ### pre-0.3 if ( ( $token =~ m/^(\\([\w\d\*]+)(?:\[$brat0\]|\{$pat_n\})*\{)($pat_n)(\}\s*)$/so )
3054 if (
3055 (
3056 $word =~
3057 m/^((?:\\protect)?\\([\w\d\*]+)(?:${extraspace_mt}\[$brat_n\]|${extraspace_mt}\{$pat_n\})*${extraspace_mt}\{)($pat_n)(\}\s*)$/so
3058 )
3059 && ( iscmd( $2, \@TEXTCMDLIST, \@TEXTCMDEXCL ) || iscmd( $2, \@MATHTEXTCMDLIST, \@MATHTEXTCMDEXCL ) )
3060 && ( !$cmdcomment || !iscmd( $2, \@CONTEXT2CMDLIST, \@CONTEXT2CMDEXCL ) )
3061 )
3062 {
3063 # Condition 1: word is a command? - if yes, $1,$2,.. will be set as above
3064 # Condition 2: word is a text command - we mark up the interior of the word. There is a separate check for MATHTEXTCMDLIST
3065 # because for $mathmarkup=WHOLE, the commands should not be split in pass1 (ie. math mode commands are not in
3066 # TEXTCMDLIST, but the interior of MATHTEXT commnds should be highlighted in both deleted and added blocks
3067 # Condition 3: But if we are in a deleted block ($cmdcomment=1) and
3068 # $2 (the command) is in context2, just treat it as an ordinary command (i.e. comment it open with $opencmd)
3069 # Because we do not want to disable this command
3070 # here we do not use $opencmd and $closecmd($opencmd is empty)
3071 print STDERR "DEBUG: Detected text |$word| but not safe command \$2: $2 \$3: $3\n." if $debug;
3072 if ( $cmd == 1 ) {
3073 push( @$retval, $closecmd );
3074 } elsif ( $cmd == 0 ) {
3075 push( @$retval, $close );
3076 }
3077 $command = $1;
3078 $commandword = $2;
3079 $closingbracket = $4;
3080 @argtext = splitlatex($3); # split textual argument into tokens
3081 # and mark it up (but we do not need openmark and closemark)
3082 # insert command with initial arguments, marked-up final argument, and closing bracket
3083 if ( $cmdcomment && iscmd( $commandword, \@CONTEXT1CMDLIST, \@CONTEXT1CMDEXCL ) ) {
3084 # context1cmd in a deleted environment; delete command itself but keep last argument, marked up
3085 push( @$retval, $opencmd );
3086 $command =~ s/\n/\n${opencmd}/sg; # repeat opencmd at the beginning of each line
3087 # argument, note that the additional comment character is included
3088 # to suppress linebreak after opening parentheses, which is important
3089 # for latexrevise
3090 push( @$retval,
3091 $command, "%\n{$AUXCMD\n", marktags( "", "", $open, $close, $opencmd, $closecmd, $comment, \@argtext ),
3092 $closingbracket );
3093 } elsif ( iscmd( $commandword,, \@MATHTEXTCMDLIST, \@MATHTEXTCMDEXCL ) ) {
3094 # MATHBLOCK pseudo command: consider all commands safe, except & and \\, \begin and \end and a few package specific one (look at UNSAFEMATHCMD definition)
3095 # Keep these commands even in deleted blocks, hence set $opencmd and $closecmd (5th and 6th argument of marktags) to
3096 # ""
3097 local @SAFECMDLIST = (".*");
3098 local @SAFECMDEXCL = ( '\\', '\\\\', @UNSAFEMATHCMD );
3099 push(
3100 @$retval, $command, marktags( "", "", $open, $close, "", "", $comment, \@argtext ) #@argtext
3101 , $closingbracket
3102 );
3103 } else {
3104 # normal textcmd or context1cmd in an added block
3105 push( @$retval,
3106 $command, marktags( "", "", $open, $close, $opencmd, $closecmd, $comment, \@argtext ),
3107 $closingbracket );
3108 }
3109 push( @$retval, $AUXCMD, "\n" ) if $cmdcomment;
3110 $cmd = -1;
3111 } elsif (
3112 $cmdcomment
3113 && ( $word =~
3114 m/^(\\([\w\d\*]+)(?:${extraspace_mt}\[$brat_n\]|${extraspace_mt}\{$pat_n\})*${extraspace_mt}\{)($pat_n)(\}\s*)/so
3115 )
3116 && iscmd( $2, \@KEEPCMDLIST, \@KEEPCMDEXCL )
3117 )
3118 {
3119 # 'keepcmd' in a deleted environment: keep the command as is
3120 push( @$retval, $close ) if $cmd == 0;
3121 push( @$retval, $word );
3122 $cmd = -1; # pretend we are at the beginning of a sequence because we do not want to add an additional $closecmd or $close before the next token, no matter what it is
3123 } else {
3124 # ordinary command
3125 push( @$retval, $opencmd ) if $cmd == -1;
3126 push( @$retval, $close, $opencmd ) if $cmd == 0;
3127 $word =~ s/\n/\n${opencmd}/sg if $cmdcomment; # if opencmd is a comment, repeat this at the beginning of every line
3128 ### print STDERR "MARKTAGS: Add command |$word|\n";
3129 push( @$retval, $word );
3130 $cmd = 1;
3131 }
3132 } else {
3133 ###print STDERR "DEBUG MARKTAGS is an ordinary word or SAFECMD command \n" if $debug;
3134 # just an ordinary word or command in SAFECMD
3135 push( @$retval, $open ) if $cmd == -1;
3136 push( @$retval, $closecmd, $open ) if $cmd == 1;
3137 ###TODO: check here if it is a command in MBOXCMD list, and surround it with \mbox{...}
3138 ### $word =~ /^\\(?!\()(\\|[`'^"~=.]|[\w*@]+)/ && iscmd($1,\@MBOXCMDLIST,\@MBOXCMDEXCL))
3139 ### but actually this check has been carried out already so can simply check if word begins with backslash
3140 if ( $word =~ /^(?:\\protect)?\\(?!\()(\\|[`'^"~=.]|[\w*@]+)(.*?)(\s*)$/s
3141 && iscmd( $1, \@MBOXCMDLIST, \@MBOXCMDEXCL ) )
3142 {
3143 # $word is a safe command in MBOXCMDLIST
3144 ###print STDERR "DEBUG Mboxsafecmd detected:$word:\n" if $debug ;
3145 push( @$retval, "\\mbox{$AUXCMD\n\\" . $1 . $2 . $3 . "}\\hskip0pt$AUXCMD\n" );
3146 } else {
3147 # $word is a normal word or a safe command (not in MBOXCMDLIST)
3148 push( @$retval, $word );
3149 }
3150 $cmd = 0;
3151 }
3152 }
3153 push( @$retval, $close ) if $cmd == 0;
3154 push( @$retval, $closecmd ) if $cmd == 1;
3155
3156 push( @$retval, $closemark ) if ($noncomment);
3157 return @$retval;
3158 }
3159
3160 #used in preprocess
3161 sub take_comments_and_newline_from_frac() {
3162 # some special magic for common usage of frac, which does not conform to the latexdiff requirements but can be made to fit
3163 # note that this is a rare exception to the general rule that the new tex can be reconstructed from the diff file
3164
3165 # regex that matches space and comment characters
3166 my $space = qr/\s|%[^\n]*?/;
3167 # \frac {abc} -> \frac{abc}
3168 # \frac1 -> \frac{1}
3169 # \frac a -> \frac{a}
3170 # \frac \lambda -> \frac{\lambda}
3171 s/\\frac(?|${space}+\{($pat_n)\}|${space}*(\d)|${space}+(\w)|${space}*(\\[a-zA-Z]+))/\\frac\{$1\}/g;
3172 # same as above for the second argument of frac
3173 s/\\frac(\{$pat_n\})(?|${space}*\{($pat_n)\}|${space}*(\d)|${space}*(\w)|${space}*(\\[a-zA-Z]+))/\\frac$1\{$2\}/g;
3174 }
3175
3176 # preprocess($string, ..)
3177 # carry out the following pre-processing steps for all arguments:
3178 # 1. Remove leading white-space
3179 # Change \{ to \QLEFTBRACE and \} to \QRIGHTBRACE and \& to \AMPERSAND
3180 # #. Change {,},\frac in comments to \CLEFTBRACE, \CRIGHTBRACE, \CFRAC
3181 # 2. mark all first empty line (in block of several) with \PAR tokens
3182 # 3. Convert all '\%' into '\PERCENTAGE ' and all '\$' into \DOLLAR to make parsing regular expressions easier
3183 # 4. Convert all \verb|some verbatim text| commands (where | can be an arbitrary character)
3184 # into \verb{hash} (also lstinline)
3185 # 5. Convert \begin{verbatim} some verbatim text \end{verbatim} into \verbatim{hash} (not only verbatim, all patterns matching VERBATIMENV)
3186 # 6. Convert _n into \SUBSCRIPTNB{n} and _{nnn} into \SUBSCRIPT{nn}
3187 # 7. Convert ^n into \SUPERSCRIPTNB{n} and ^{nnn} into \SUPERSCRIPT{nn}
3188 # 8. a. Convert $$ $$ into \begin{DOLLARDOLLAR} \end{DOLLARDOLLAR}
3189 # b. Convert \[ \] into \begin{SQUAREBRACKET} \end{SQUAREBRACKET}
3190 # 9. Convert all picture environmentent (\begin{PICTUREENV} .. \end{PICTUREENV} \PICTUREBLOCKenv
3191 # For math-mode COARSE,WHOLE or NONE option -convert all \begin{MATH} .. \end{MATH}
3192 # into \MATHBLOCKmath{...} commands, where MATH/math is any valid math environment
3193
3194 # 10. Add final token STOP to the very end. This is put in because the algorithm works better if the last token is identical. This is removed again in postprocessing.
3195 #
3196 # NB: step 6 and 7 is likely to convert some "_" inappropriately, e.g. in file
3197 # names or labels but it does not matter because they are converted back in the postprocessing step
3198 # Returns: leading white space removed in step 1
3199 sub preprocess {
3200 for (@_) {
3201
3202 # change in \verb and similar commands - note that I introduce an extra space here so that the
3203 # already hashed variants do not trigger again
3204 # transform \lstinline{...}
3205 # s/\\lstinline(\[$brat0\])?(\{(?:.*?)\})/"\\DIFlstinline". $1 ."{". tohash(\%verbhash,"$2") ."}"/esg;
3206 # s/\\lstinline(\[$brat0\])?((\S).*?\2)/"\\DIFlstinline". $1 ."{". tohash(\%verbhash,"$2") ."}"/esg;
3207 s/\\lstinline((?:\[$brat_n\])?)(\{(?:.*?)\})/"\\DIFlstinline". $1 ."{". tohash(\%verbhash,"$2") ."}"/esg;
3208 s/\\lstinline((?:\[$brat_n\])?)(([^\s\w]).*?\3)/"\\DIFlstinline". $1 ."{". tohash(\%verbhash,"$2") ."}"/esg;
3209 s/\\(verb\*?|lstinline)([^\s\w])(.*?)\2/"\\DIF${1}{". tohash(\%verbhash,"${2}${3}${2}") ."}"/esg;
3210
3211 s/(?<!\\)\\%/\\PERCENTAGE /g; # (?<! is negative lookbehind assertion to prevent \\% from being converted
3212
3213 # Change \{ to \QLEFTBRACE, \} to \QRIGHTBRACE, and \& to \AMPERSAND
3214 s/(?<!\\)\\\{/\\QLEFTBRACE /sg;
3215 s/(?<!\\)\\\}/\\QRIGHTBRACE /sg;
3216 s/(?<!\\)\\&/\\AMPERSAND /sg;
3217
3218
3219 # replace {,} with \CLEFTBRACE,\CRIGHTBRACE
3220 1 while s/(%.*)\{(.*)$/$1\\CLEFTBRACE $2/mg;
3221 1 while s/(%.*)\}(.*)$/$1\\CRIGHTBRACE $2/mg;
3222
3223 s/(?<!\\)\\\$/\\DOLLAR /g; # (?<! is negative lookbehind assertion to prevent \\$ from being converted
3224 s/\\begin\{($VERBATIMENV)\}(.*?)\\end\{\1\}/"\\${1}{". tohash(\%verbhash,"${2}") . "}"/esg;
3225 s/\\begin\{($VERBATIMLINEENV)\}(.*?)\\end\{\1\}/"\\begin{$1}". linecomment($2) . "\\end{$1}"/esg;
3226
3227 # replace {,}, \frac,_,^ in comments with \CLEFTBRACE,\CRIGHTBRACE, \CFRAC, \CUNDERSCORE, \CCARET, respectively to protect from special treatment
3228 # note that we need to do this after having turned verbatim environments into comments
3229 # (an exception is for {,} as otherwise the processing of the verbatim environments themselves might be affected)
3230 # We solve this by simpling doint the CLEFTBRACE,CRIGHTBRACE conversion twice.
3231 1 while s/(%.*)\{(.*)$/$1\\CLEFTBRACE $2/mg;
3232 1 while s/(%.*)\}(.*)$/$1\\CRIGHTBRACE $2/mg;
3233 1 while s/(%.*)\\frac(.*)$/$1\\CFRAC $2/mg;
3234 1 while s/(%.*)\\sqrt(.*)$/$1\\CSQRT $2/mg;
3235 1 while s/(%.*)_(.*)$/$1\\CUNDERSCORE $2/mg;
3236 1 while s/(%.*)^(.*)$/$1\\CCARET $2/mg;
3237
3238 # mark all first empty line (in block of several) with \PAR tokens
3239 s/\n(\s*?)\n((?:\s*\n)*)/\n$1\\PAR\n$2/g;
3240 # Convert _n or _\cmd into \SUBSCRIPTNB{n} or \SUBSCRIPTNB{\cmd} and _{nnn} into \SUBSCRIPT{nn}
3241 1 while s/(?<!\\)_(\s*([^{\\\s]|\\\w+))/\\SUBSCRIPTNB{$1}/g;
3242 1 while s/(?<!\\)_(\s*{($pat_n)})/\\SUBSCRIPT$1/g;
3243 # Convert ^n into \SUPERSCRIPTNB{n} and ^{nnn} into \SUPERSCRIPT{nn}
3244 1 while s/(?<!\\)\^(\s*([^{\\\s]|\\\w+))/\\SUPERSCRIPTNB{$1}/g;
3245 1 while s/(?<!\\)\^(\s*{($pat_n)})/\\SUPERSCRIPT$1/g;
3246 # Convert \sqrt{n} into \SQRT{n} and \sqrt nn into SQRTNB{nn}
3247 1 while s/(?<!\\)\\sqrt(\s*([^{\\\s]|\\\w+))/\\SQRTNB{$1}/g;
3248 1 while s/(?<!\\)\\sqrt(\s*{($pat_n)})/\\SQRT$1/g;
3249 # Convert $$ $$ into \begin{DOLLARDOLLAR} \end{DOLLARDOLLAR}
3250 s/\$\$(.*?)\$\$/\\begin{DOLLARDOLLAR}$1\\end{DOLLARDOLLAR}/sg;
3251 # Convert \[ \] into \begin{SQUAREBRACKET} \end{SQUAREBRACKET}
3252 s/(?<!\\)\\\[/\\begin{SQUAREBRACKET}/sg;
3253 s/(?<!\\)\\\]/\\end{SQUAREBRACKET}/sg;
3254
3255 # Convert all picture environmentent (\begin{PICTUREENV} .. \end{PICTUREENV} \PICTUREBLOCKenv
3256 s/\\begin\{($PICTUREENV)}(.*?)\\end\{\1}/\\PICTUREBLOCK$1\{$2\}/sg;
3257 # For math-mode COARSE,WHOLE or NONE option -convert all \begin{MATH} .. \end{MATH}
3258 # into \MATHBLOCKMATH{...} commands, where MATH is any valid math environment
3259 # Also convert all array environments into ARRAYBLOCK environments.
3260 # Where these environments have arguments they become optional arguments to the MATHBLOCK command enclosed in < > brackets
3261 # Example: \begin{alignat}{3} ... \end{alignat} will turn into \MATHBLOCKalignat[{3}]{ ... }
3262
3263 if ( $mathmarkup != FINE ) {
3264 # DIFANCHORARRB and DIFANCHORARRE, DIFANCHORMATHB and DIFANCHORMATHE markers are inserted here to encourage the matching algorithm
3265 # to always match up the closing brace. Otherwise sometimes one ends up with a situation where
3266 # the closing brace is deleted and added at another point. The deleted closing brace is then
3267 # prevented by a %DIFDELCMD, leading to material leaking in or out of the math environment.
3268 # The anchors are removed in post-processing again. (note that they are simple text to cause least amount of complications
3269 # Admittedly, this is something of a hack and will not always work. If it does not, then one needs to
3270 # resort to WHOLE or FINE, or NONE math mode processing.
3271 # Previous construction had problems with nested \begin{array} ... \end{array} constructions, so we convert the inner ones
3272 # first, and then iterate with the "1 while" construction to take care of the outer ones
3273 1 while
3274 s/\\begin\{($ARRENV)\}((?:.(?!\\begin\{\1\}))*?)\\end\{\1}/\\ARRAYBLOCK$1\{$2\\DIFANCHORARRB \}\\DIFANCHORARRE /sg;
3275
3276 take_comments_and_newline_from_frac();
3277
3278 # Convert Math environments with arguments
3279 s/\\begin\{($MATHENV|$MATHARRENV|SQUAREBRACKET)\}((?:\[$brat_n\])|(?:\{$pat_n\}))+(.*?)\\end\{\1\}/\\MATHBLOCK$1\[$2\]\{$3\\DIFANCHORMATHB \}\\DIFANCHORMATHE /sg;
3280 # Convert Math environments without arguments
3281 s/\\begin\{($MATHENV|$MATHARRENV|SQUAREBRACKET)\}(.*?)\\end\{\1\}/\\MATHBLOCK$1\{$2\\DIFANCHORMATHB \}\\DIFANCHORMATHE /sg;
3282 }
3283
3284 # add final token " STOP"
3285 $_ .= " STOP";
3286 }
3287 }
3288
3289 # $expanded=linecomment($string)
3290 #preface all lines with verbatim marker (usually DIFVRB)
3291 sub linecomment {
3292 my @verbatimlines = split( "\n", $_[0] );
3293 # the first line needs special treatment - we do want to retain optional arguments as is but wrap the remainder also with VERBCOMMENT
3294 ### print STDERR "DEBUG: before verbatimlines[0] = ",$verbatimlines[0],"\n";
3295 $verbatimlines[0] =~ s/^((?:\s*\[$brat_n\])?\s*)([^\s\[].*)/ defined($2) ? ( "$1\%$VERBCOMMENT$2" ) : ( $1 )/e;
3296 ### print STDERR "DEBUG: after verbatimlines[0] = ",$verbatimlines[0],"\n";
3297 return ( join( "\n%$VERBCOMMENT", @verbatimlines ) . "\n" );
3298 }
3299
3300 # $simple=reverselinecomment($env $string)
3301 # remove DIFVRB comments but leave changed lines marked
3302 sub reverselinecomment {
3303 my ( $environment, $verbatimtext ) = @_;
3304 ### print STDERR "DEBUG REVERSELINECOMMENT input: $environment,|$verbatimtext|\n" if $debug;
3305 # remove markup added by latexdiff
3306 # (this should occur only if the type of verbatim environment was changed)
3307 # (note that this destroys some information in old file)
3308 # in theory I could save it by moving it out of the verbatim environment
3309 # but this requires more bookkeeping and is probably not necessary)
3310 $verbatimtext =~ s/\\DIFaddbegin //g;
3311 $verbatimtext =~ s/\\DIFaddend //g;
3312 $verbatimtext =~ s/\\DIFdelbegin //g;
3313 $verbatimtext =~ s/\\DIFdelend //g;
3314 $verbatimtext =~ s/$DELCMDOPEN.*//g;
3315
3316 # remove DIFVRB mark
3317 $verbatimtext =~ s/%$VERBCOMMENT//g;
3318
3319 # remove part of the markup in changed lines
3320 # if any of these substitution was made, then there was at least
3321 # one changed line, and we have to extend the style
3322 if ( $verbatimtext =~ s/$VERBCOMMENT//g ) {
3323 # in the next line we add ~alsolanguage~ modifier, but also deletes the rest of the line after the optional argument, as lstlisting commands gets sometimes
3324 # very confused by what is there (and othertimes seems to ignore this anyway)
3325 unless ( $verbatimtext =~ s/^(\s*)\[($brat_n)\](.*)\n/$1\[$2,alsolanguage=DIFcode\]\n/ ) {
3326 if ( $verbatimtext =~ m/^\s*\n/ ) {
3327 $verbatimtext = "[alsolanguage=DIFcode]" . $verbatimtext;
3328 } else {
3329 $verbatimtext = "[alsolanguage=DIFcode]\n" . $verbatimtext;
3330 }
3331 }
3332 # There is a bug in listings package (at least v1.5b) for empty comments where the actual comment command is not made invisible
3333 # I therefore have to introduce an artificial '-' character at the end of empty added or deleted lines
3334 $verbatimtext =~ s/($DELCOMMENT\s*)$/$1-/mg;
3335 $verbatimtext = "\\DIFmodbegin\n\\begin{${environment}}${verbatimtext}\\end{${environment}}\n\\DIFmodend";
3336 } else {
3337 $verbatimtext = "\\begin{${environment}}${verbatimtext}\\end{${environment}}";
3338 }
3339 ### print STDERR "DEBUG REVERSELINECOMMENT output: |$verbatimtext|\n" if $debug;
3340 return ($verbatimtext);
3341 }
3342
3343 #hashstring=tohash(\%hash,$string)
3344 # creates a hash value based on string and stores in %hash
3345 sub tohash {
3346 my ( $hash, $string ) = @_;
3347 my ( @arr, $val );
3348 my ( $sum, $i ) = ( 0, 1 );
3349 my ($hstr);
3350
3351 @arr = unpack( 'c*', $string );
3352
3353 while (1) {
3354 foreach $val (@arr) {
3355 $sum += $i * $val;
3356 $i++;
3357 }
3358 $hstr = "$sum";
3359 last unless ( defined( $hash->{$hstr} ) && $string ne $hash->{$hstr} );
3360 # else found a duplicate HASH need to repeat for a higher hash value
3361 }
3362 $hash->{$hstr} = $string;
3363 ### print STDERR "Hash:$hstr: Content:$string:\n";
3364 return ($hstr);
3365 }
3366
3367 #string=fromhash(\%hash,$fromstring)
3368 # restores string value stored in hash
3369 #string=fromhash(\%hash,$fromstring,$prependstring)
3370 # additionally begins each line with prependstring
3371 sub fromhash {
3372 my ( $hash, $hstr ) = ( $_[0], $_[1] );
3373 my $retstr = $hash->{$hstr};
3374 if ( $#_ >= 2 ) {
3375 $retstr =~ s/^/$_[2]/mg;
3376 }
3377 return $retstr;
3378 }
3379
3380 # stripdelcmpopen(string)
3381 # return string with $DELCMDOPEN removed
3382 sub stripdelcmdopen {
3383 my ($str) = $_[0];
3384 $str =~ s/${DELCMDOPEN}//mg;
3385 return $str;
3386 }
3387
3388 # writedebugfile(string, label)
3389 # if $debug set writes <string> to file latexdiff.debug.<label>
3390 # otherwise do nothing
3391 sub writedebugfile {
3392 my ( $string, $label ) = @_;
3393 if ($debug) {
3394 open( RAWDIFF, ">", "latexdiff.debug." . $label );
3395 print RAWDIFF $string;
3396 close(RAWDIFF);
3397 }
3398 }
3399
3400 # postprocess($string, ..)
3401 # carry out the following post-processing steps for all arguments:
3402 # * Remove STOP token from the end
3403 # * Replace \RIGHTBRACE by }
3404 # * If option --no-del is set delete all deleted blocks
3405 # 1. Check all deleted blocks:
3406 # a.where a deleted block contains a matching \begin and
3407 # \end environment (these will be disabled by a %DIFDELCMD statements), for selected environments enable
3408 # these commands again (such that for example displayed math in a deleted equation
3409 # is properly within math mode. For math mode environments replace numbered equation
3410 # environments with their display only variety (so that equation numbers in new file and
3411 # diff file are identical). Where the correct type of math environment cannot be determined
3412 # use a place holder MATHMODE
3413 # b.where one of the commands matching $COUNTERCMD is used as a DIFAUXCMD, add a statement
3414 # subtracting one from the respective counter to keep numbering consistent with new file
3415 # Replace all MATHMODE environment commands by the correct environment to achieve matching
3416 # pairs
3417 # c. Convert MATHBLOCKmath commands to their uncounted numbers (e.g. convert equation -> displaymath
3418 # (environments defined in $MATHENV will be replaced by $MATHREPL, and environments in $MATHARRENV
3419 # will be replaced by their equivalent with a * appended, e.g. align -> align*
3420 # d. If in-line math mode contains array environment, enclose the whole environment in \mbox'es
3421 # d. place \cite commands in mbox'es (for UNDERLINE style)
3422 #
3423 # For added blocks:
3424 # c. If in-line math mode contains array environment, enclose the whole environment in \mbox'es
3425 # d. place \cite commands in mbox'es (for UNDERLINE style)
3426 #
3427 # 2. If math-mode COARSE,WHOLE or NONE option set: Convert \MATHBLOCKmath{..} commands back to environments
3428 #
3429 # Convert all PICTUREblock{..} commands back to the appropriate environments
3430 # 3. Convert DIFadd, DIFdel, DIFaddbegin , ... into FL varieties
3431 # within floats (currently recognised float environments: plate,table,figure
3432 # plus starred varieties).
3433 # 4. Remove empty %DIFDELCMD < lines
3434 # 4. Convert \begin{SQUAREBRACKET} \end{SQUAREBRACKET} into \[ \]
3435 # Convert \begin{DOLLARDOLLAR} \end{DOLLARDOLLAR} into $$ $$
3436 # 5. Convert \SUPERSCRIPTNB{n} into ^n and \SUPERSCRIPT{nn} into ^{nnn}
3437 # 6. Convert \SUBSCRIPTNB{n} into _n and \SUBCRIPT{nn} into _{nnn}
3438 # 7. Expand hashes of verb and verbatim environments
3439 # 8. Convert '\PERCENTAGE ' back into '\%' and '\DOLLAR ' into '\$'
3440 # 9.. remove all \PAR tokens
3441 # 10. package specific processing: endfloat: make sure \begin{figure} and \end{figure} are always
3442 # on a line by themselves, similarly for table environment
3443 # 4, undo renaming of the \begin, \end,{,} in comments
3444 # Change \QLEFTBRACE, \QRIGHTBRACE,\AMPERSAND to \{,\},\&
3445 #
3446 # Note have to manually synchronize substitution commands below and
3447 # DIF.. command names in the header
3448 sub postprocess {
3449 my ( $begin, $len, $float, $delblock, $addblock ); ### $cnt
3450 # second level blocks
3451 my ( $begin2, $len2, $eqarrayblock, $eqblock, $mathblock ); ### $cnt2
3452
3453 my ( @textparts, @newtextparts, @liststack, $listtype, $listlast );
3454
3455 my ( @itemargs, $itemarg );
3456
3457 for (@_) {
3458 # change $'s in comments to something harmless
3459 1 while s/(%.*)\$/$1DOLLARDIF/mg;
3460
3461 # Remove final STOP token
3462 s/ STOP$//;
3463 # Replace \RIGHTBRACE in comments by \MBLOCKRIGHTBRACE
3464 # the only way to get these is as %DIFDELCMD < \RIGHTBRACE construction
3465 # This essentially marks closing right braces of MATHBLOCK environments, which did not get matched
3466 # up. This case should be rare, so I just leave this in the diff file output. Not really elegant
3467 # but can still be dealt with later if it results in problems.
3468 s/%DIFDELCMD < \\RIGHTBRACE/%DIFDELCMD < \\MBLOCKRIGHTBRACE/g;
3469 # Replace \RIGHTBRACE by }
3470 s/\\RIGHTBRACE/}/g;
3471
3472 # Optional: Remove deleted block entirely
3473 if ($onlyadditions) {
3474 s/\\DIFdelbegin.*?\\DIFdelend//sg;
3475 #remove deleted comments
3476 s/%$DELCOMMENT.*\n//g;
3477 }
3478
3479 # Check all deleted blocks: where a deleted block contains a matching \begin and
3480 # \end environment (these will be disabled by a %DIFDELCMD statements), enable
3481 # these commands again (such that for example displayed math in a deleted equation
3482 # is properly within math mode). For math mode environments replace numbered equation
3483 # environments with their display only variety (so that equation numbers in new file and
3484 # diff file are identical)
3485 writedebugfile( $_, 'postprocess1' );
3486
3487 while (m/\\DIFdelbegin.*?\\DIFdelend/sg) {
3488 # special processing within each deleted block
3489 ### while ( m/\\DIFdelbegin.*?\\DIFdelend/sg ) {
3490 ### print STDERR "DEBUG Match delblock \n||||$&||||\n at ",pos,"\n";
3491 my $arrenv; # dummy variable only needed within this block
3492 my @symbols; # another temporary variable
3493 $len = length($&);
3494 $begin = pos($_) - $len;
3495 $delblock = $&;
3496 ### A much simpler method for math replacement might follow this strategy (can recycle part of the commands below for following
3497 ### this strategy:
3498 ### 1. a Insert aux commands \begin{MATHMODE} or \end{MATHMODE} for all deleted commands opening or closing displayed math mode
3499 ### b Insert aux commands \begin{MATHARRMODE} or \end{MATHARRMODE} for all deleted commands opening or closing math array mode
3500 ### 2 Replace MATHMODE and MATHARRMODE by correct pairing if appropriate partner math command is found in text
3501 ### 3 a Replace remaining \begin{MATHMODE}...\end{MATHMODE} pairs with \begin{$MATHREPL}..\end{$MATHREPL}
3502 ### b Replace remaining \begin{MATHARRMODE}...\end{MATHARRMODE} pairs with \begin{$MATHREPL}..\end{$MATHREPL}
3503 ### 4 Delete all aux command math mode pairs which have simply comments or empty lines between them
3504 ### As written this won't actually work!
3505
3506 ### Most general case: allow all included environments
3507 ### $delblock=~ s/(\%DIFDELCMD < \s*\\begin\{(\w*\*?)\}\s*?\n)(.*?)(\%DIFDELCMD < \s*\\end\{\2\})/$1\\begin{$2}$AUXCMD\n$3\n\\end{$2}$AUXCMD\n$4/sg;
3508 ### (.*?[^\n]?)\n? construct is necessary to avoid empty lines in math mode, which result in
3509 ### an error
3510 # displayed math environments
3511 ###0.5: $delblock=~ s/(\%DIFDELCMD < \s*\\begin\{((?:$MATHENV)|SQUAREBRACKET)\}\s*?(?:$DELCMDCLOSE|\n))(.*?[^\n]?)\n?(\%DIFDELCMD < \s*\\end\{\2\})/\\begin{$MATHREPL}$AUXCMD\n$1$3\n\\end{$MATHREPL}$AUXCMD\n$4/sg;
3512
3513 if ( $mathmarkup == FINE ) {
3514 # if block contains both beginning and and markers for an explicit math environment, restore opening and closing commands
3515 $delblock =~
3516 s/(\%DIFDELCMD < \s*\\begin\{((?:$MATHENV)|SQUAREBRACKET)\}.*?(?:$DELCMDCLOSE|\n))(.*?[^\n]?)\n?(\%DIFDELCMD < \s*\\end\{\2\})/\\begin{$MATHREPL}$AUXCMD\n$1$3\n\\end{$MATHREPL}$AUXCMD\n$4/sg;
3517 # also transform the opposite pair \end{displaymath} .. \begin{displaymath} but we have to be careful not to interfere with the results of the transformation in the line directly above
3518 ### pre-0.42 obsolete version which did not work on eqnarray test $delblock=~ s/(?<!${AUXCMD}\n)(\%DIFDELCMD < \s*\\end\{($MATHENV)\}\s*?\n)(.*?[^\n]?)\n?(?<!${AUXCMD}\n)(\%DIFDELCMD < \s*\\begin\{\2\})/$1\\end{$MATHREPL}$AUXCMD\n$3\n\\begin{$MATHREPL}$AUXCMD\n$4/sg;
3519 ###0.5: $delblock=~ s/(?<!${AUXCMD}\n)(\%DIFDELCMD < \s*\\end\{((?:$MATHENV)|SQUAREBRACKET)\}\s*?(?:$DELCMDCLOSE|\n))(.*?[^\n]?)\n?(?<!${AUXCMD}\n)(\%DIFDELCMD < \s*\\begin\{\2\})/\\end{MATHMODE}$AUXCMD\n$1$3\n\\begin{MATHMODE}$AUXCMD\n$4/sg;
3520 $delblock =~
3521 s/(?<!${AUXCMD}\n)(\%DIFDELCMD < \h*\\end\{((?:$MATHENV)|SQUAREBRACKET)\}.*?(?:$DELCMDCLOSE|\n))(.*?[^\n]?)\n?(?<!${AUXCMD}\n)(\%DIFDELCMD < \h*\\begin\{\2\})/\\end\{MATHMODE\}$AUXCMD\n$1$3\n\\begin\{MATHMODE\}$AUXCMD\n$4/sg;
3522
3523 # now look for unpaired %DIFDELCMD < \begin{MATHENV}; if found add \begin{$MATHREPL} and insert \end{$MATHREPL}
3524 # just before end of block; again we use look-behind assertion to avoid matching constructions which have already been converted
3525 if ( $delblock =~
3526 s/(?<!${AUXCMD}\n)(\%DIFDELCMD < \h*\\begin\{((?:$MATHENV)|SQUAREBRACKET)\}\s*?(?:$DELCMDCLOSE|\n))/$1\\begin{$MATHREPL}$AUXCMD\n/sg
3527 )
3528 {
3529 ### print STDERR "BINGO: begin block: \nBefore: |" . substr($_,$begin,$len) . "|\n" if $debug ;
3530 $delblock =~ s/(\\DIFdelend$)/\\end{$MATHREPL}$AUXCMD\n$1/s;
3531 ### print STDERR "After: |" . $delblock . "|\n\n" if $debug ;
3532 }
3533 # now look for unpaired %DIFDELCMD < \end{MATHENV}; if found add \end{MATHMODE} and insert \begin{MATHMODE}
3534 # just before end of block; again we use look-behind assertion to avoid matching constructions which have already been converted
3535 if ( $delblock =~
3536 s/(?<!${AUXCMD}\n)(\%DIFDELCMD < \h*\\end\{((?:$MATHENV)|SQUAREBRACKET)\}\s*?(?:$DELCMDCLOSE|\n))/$1\\end\{MATHMODE\}$AUXCMD\n/sg
3537 )
3538 {
3539 ### print STDERR "BINGO: end block:\nBefore: |" . substr($_,$begin,$len) . "|\n" if $debug;
3540 $delblock =~ s/(\\DIFdelend$)/\\begin\{MATHMODE\}$AUXCMD\n$1/s;
3541 ### print STDERR "After: |" . $delblock . "|\n\n" if $debug ;
3542 }
3543
3544 ### pre-0.42 # same as above for special case \[.\] (latex abbreviation for displaymath)
3545 ### pre-0.42 $delblock=~ s/(\%DIFDELCMD < \s*\\\[\s*?\n())(.*?[^\n]?)\n?(\%DIFDELCMD < \s*\\\])/$1\\\[$AUXCMD\n$3\n\\\]$AUXCMD\n$4/sg;
3546 ### pre-0.42 $delblock=~ s/(?<!${AUXCMD}\n)(\%DIFDELCMD < \s*\\\]\s*?\n())(.*?[^\n]?)\n?(?<!${AUXCMD}\n)(\%DIFDELCMD < \s*\\\[)/$1\\\]$AUXCMD\n$3\n\\\[$AUXCMD\n$4/sg;
3547 # equation array environment
3548 ###pre-0.3 $delblock=~ s/(\%DIFDELCMD < \s*\\begin\{($MATHARRENV)\}\s*?\n)(.*?)(\%DIFDELCMD < \s*\\end\{\2\})/$1\\begin{$MATHARRREPL}$AUXCMD\n$3\n\\end{$MATHARRREPL}$AUXCMD\n$4/sg;
3549 ###0.5 $delblock=~ s/(\%DIFDELCMD < \s*\\begin\{($MATHARRENV)\}\s*?(?:$DELCMDCLOSE|\n))(.*?[^\n]?)\n?(\%DIFDELCMD < \s*\\end\{\2\})/\\begin{$MATHARRREPL}$AUXCMD\n$1$3\n\\end{$MATHARRREPL}$AUXCMD\n$4/sg;
3550 ###1.3.2 $delblock=~ s/(\%DIFDELCMD < \s*\\begin\{($MATHARRENV)\}.*?(?:$DELCMDCLOSE|\n))(.*?[^\n]?)\n?(\%DIFDELCMD < \s*\\end\{\2\})/\\begin{$MATHARRREPL}$AUXCMD\n$1$3\n\\end{$MATHARRREPL}$AUXCMD\n$4/sg;
3551 # Example Input: %DIFDELCMD < \begin{alignat}{2} \n\exp(ix)&=&\cos(x)+i\sin(x)\n%DIFDECMD < \end{alignat}
3552 # < $1 <$2 >><$3> < $4 ><$5 >
3553 # Example Output:\begin{alignat*}{2}%DIFAUXCMD\n\%DIFDELCMD\begin{align}\n\exp(ix)&=&\cos(x)+i\sin(x)\n\end{align*}%DIFAUXCMD\n%DIFDELCMD > \end{alignat*}
3554 $delblock =~
3555 s/(\%DIFDELCMD < \s*\\begin\{($MATHARRENV)\}(.*?)(?:$DELCMDCLOSE|\n))(.*?[^\n]?)\n?(\%DIFDELCMD < \s*\\end\{\2\})/\\begin{$2*}$3$AUXCMD\n$1$4\n\\end{$2*}$AUXCMD\n$5/sg;
3556 ### pre-0.42 obsolete version which did not work on eqnarray test $delblock=~ s/(?<!${AUXCMD}\n)(\%DIFDELCMD < \s*\\end\{($MATHARRENV)\}\s*?\n)(.*?[^\n]?)\n?(?<!${AUXCMD}\n)(\%DIFDELCMD < \s*\\begin\{\2\})/$1\\end{$MATHARRREPL}$AUXCMD\n$3\n\\begin{$MATHARRREPL}$AUXCMD\n$4/sg;
3557 $delblock =~
3558 s/(?<!${AUXCMD}\n)(\%DIFDELCMD < \h*\\end\{($MATHARRENV)\}\s*?(?:$DELCMDCLOSE|\n))(.*?[^\n]?)\n?(?<!${AUXCMD}\n)(\%DIFDELCMD < \h*\\begin\{\2\})/\\end{MATHMODE}$AUXCMD\n$1$3\n\\begin{MATHMODE}$AUXCMD\n$4/sg;
3559 ### print STDERR "STEP1: |" . $delblock . "|\n\n" if $debug ;
3560
3561 # now look for unpaired %DIFDELCMD < \begin{MATHARRENV}; if found add \begin{$MATHARRREPL} and insert \end{$MATHARRREPL}
3562 # just before end of block; again we use look-behind assertion to avoid matching constructions which have already been converted
3563 if ( $delblock =~
3564 s/(?<!${AUXCMD}\n)(\%DIFDELCMD < \h*\\begin\{($MATHARRENV)\}(.*?)(?:$DELCMDCLOSE|\n))/$1\\begin{$2*}$3$AUXCMD\n/sg
3565 )
3566 {
3567 $arrenv = $2;
3568 $delblock =~ s/(\\DIFdelend$)/\\end{$arrenv*}$AUXCMD\n$1/s;
3569 }
3570 ### print STDERR "STEP2: |" . $delblock . "|\n\n" if $debug ;
3571
3572 # now look for unpaired %DIFDELCMD < \end{MATHENV}; if found add \end{MATHMODE} and insert \begin{MATHMODE}
3573 # just before end of block; again we use look-behind assertion to avoid matching constructions which have already been converted
3574 if ( $delblock =~
3575 s/(?<!${AUXCMD}\n)(\%DIFDELCMD < \h*\\end\{($MATHARRENV)\}\s*?(?:$DELCMDCLOSE|\n))/$1\\end{MATHMODE}$AUXCMD\n/sg
3576 )
3577 {
3578 $delblock =~ s/(\\DIFdelend$)/\\begin{MATHMODE}$AUXCMD\n$1/s;
3579 }
3580
3581 # parse $delblock for deleted and reinstated eqnarray* environments - within those reinstate \\ and & commands
3582 ### while ( $delblock =~ m/\\begin{$MATHARRREPL}$AUXCMD\n.*?\n\\end{$MATHARRREPL}$AUXCMD\n/sg ) {
3583 ### while ( $delblock =~ m/\\begin\Q{$MATHARRREPL}$AUXCMD\E\n.*?\n\\end\Q{$MATHARRREPL}$AUXCMD\E\n/sg ) {
3584 while ( $delblock =~ m/\\begin\{$MATHARRENV\*}[^\n]*?$AUXCMD\n.*?\n\\end\{$MATHARRENV\*\}$AUXCMD\n/sg ) {
3585 ### print STDERR "DEBUG Match eqarrayblock $& at ",pos,"\n";
3586 $len2 = length($&);
3587 $begin2 = pos($delblock) - $len2;
3588 $eqarrayblock = $&;
3589 # reinstate deleted & and \\ commands
3590 ### $eqarrayblock=~ s/(\%DIFDELCMD < \s*(\&|\\\\)\s*?(?:$DELCMDCLOSE|\n))/$1$2$AUXCMD\n/sg ;
3591 $eqarrayblock =~ s/(\%DIFDELCMD < (.*?(?:\&|\\\\).*)(?:$DELCMDCLOSE|\n))/
3592 # The pattern captures comments with at least one of & or \\
3593 @symbols= split(m@((?:&|\\\\)\s*)@,$2); # extract & and \\ and other material from sequence
3594 @symbols= grep ( m@&|\\\\\s*@, @symbols); # select & and \\ (and subsequent spaces)
3595 "$1@symbols$AUXCMD\n"
3596 /eg;
3597 ### print STDERR "Modified block:|$eqarrayblock|\n" if $debug;
3598 # splice in modified block
3599 substr( $delblock, $begin2, $len2 ) = $eqarrayblock;
3600 pos($delblock) = $begin2 + length($eqarrayblock);
3601 }
3602
3603 } elsif ( $mathmarkup == COARSE || $mathmarkup == WHOLE ) {
3604 # Convert MATHBLOCKmath commands to their uncounted numbers (e.g. convert equation -> displaymath
3605 # (environments defined in $MATHENV will be replaced by $MATHREPL, and environments in $MATHARRENV
3606 # will be replaced by their starred variety
3607 $delblock =~ s/\\MATHBLOCK($MATHENV)((?:\[$brat_n\])?)\{($pat_n)\}/\\MATHBLOCK$MATHREPL$2\{$3\}/sg;
3608 $delblock =~ s/\\MATHBLOCK($MATHARRENV)((?:\[$brat_n\])?)\{($pat_n)\}/\\MATHBLOCK$1\*$2\{$3\}/sg;
3609 }
3610
3611 # Replacing math array environments with their starred varieties in deleted blocks as implemented now causes double asterisks
3612 # in situation where there had been starred already, e.g. \begin{alignat*} is turned into \begin{alignat**}
3613 # The following command seeks to undo this double-starring. It is a little bit of a hack because it relies on the fact that **
3614 # double-starred math array environment does not occur naturally
3615 $delblock =~ s/($MATHARRENV)(?<=\*)\*/$1/sg;
3616
3617 print STDERR "DELBLOCK after maths processing: |" . $delblock . "|\n\n" if $debug;
3618
3619 # Reinstate completely deleted list environments. note that items within the
3620 # environment will still be commented out. They will be restored later
3621 $delblock =~
3622 s/(\%DIFDELCMD < \s*\\begin\{($LISTENV)\}\s*?(?:\n|$DELCMDCLOSE))(.*?)(\%DIFDELCMD < \s*\\end\{\2\})/{
3623 ### # block within the search; replacement environment
3624 ### "$1\\begin{$2}$AUXCMD\n". restore_item_commands($3). "\n\\end{$2}$AUXCMD\n$4";
3625 "$1\\begin{$2}$AUXCMD\n$3\n\\end{$2}$AUXCMD\n$4";
3626 }/esg;
3627 ### $delblock=~ s/\\begin\{$MATHENV}$AUXCMD/\\begin{$MATHREPL}$AUXCMD/g;
3628 ### $delblock=~ s/\\end\{$MATHENV}$AUXCMD/\\end{$MATHREPL}$AUXCMD/g;
3629 ### $delblock=~ s/\\begin\{$MATHARRENV}$AUXCMD/\\begin{$MATHARRREPL}$AUXCMD/g;
3630 ### $delblock=~ s/\\end\{$MATHARRENV}$AUXCMD/\\end{$MATHARRREPL}$AUXCMD/g;
3631
3632 # b.where one of the commands matching $COUNTERCMD is used as a DIFAUXCMD, add a statement
3633 # subtracting one from the respective counter to keep numbering consistent with new file
3634 $delblock =~
3635 s/\\($COUNTERCMD)((?:${extraspace}\[$brat_n\]${extraspace}|${extraspace}\{$pat_n\})*\s*${AUXCMD}\n)/\\$1$2\\addtocounter{$1}{-1}${AUXCMD}\n/sg;
3636
3637 # bb. disable active labels within deleted blocks (i.e. those not commented out) (as these are not safe commands, this should normally only
3638 # happen within deleted maths blocks
3639 ### $delblock=~ s/(?<!$DELCMDOPEN)(\\$LABELCMD(?:${extraspace})\{(?:[^{}])*\}[\t ]*)\n?/${DELCMDOPEN}$1${DELCMDCLOSE}/smg ;
3640 ### previous line caused trouble as by issue #90 I might need to modify this
3641 $delblock =~ s/^([^%]*)(\\$LABELCMD(?:${extraspace})\{(?:[^{}])*\}[\t ]*)\n?/$1${DELCMDOPEN}$2${DELCMDCLOSE}/smg;
3642 ### print STDERR "<<<$delblock>>>\n" if $debug;
3643
3644 # c. If in-line math mode contains array environment, enclose the whole environment in \mbox'es
3645 while ( $delblock =~ m/($math)(\s*)/sg ) {
3646 ## print STDERR "DEBUG Delblock Match math $& at ",pos,"\n";
3647 $len2 = length($&);
3648 $begin2 = pos($delblock) - $len2;
3649 $mathblock = "%\n\\mbox{$AUXCMD\n$1\n}$AUXCMD\n";
3650 next unless ( $mathblock =~ /ARRAYBLOCK/ or $mathblock =~ m/\{$ARRENV\}/ );
3651 substr( $delblock, $begin2, $len2 ) = $mathblock;
3652 pos($delblock) = $begin2 + length($mathblock);
3653 }
3654 ### if ($CITE2CMD) {
3655 ###### ${extraspace}(?:\[$brat0\]${extraspace}){0,2}\{$pat_n\})) .*?%%%\n
3656 ### $delblock=~s/($DELCMDOPEN\s*\\($CITE2CMD)(.*)$DELCMDCLOSE)/
3657 ### # Replacement code
3658 ### {my ($aux,$all);
3659 ### $aux=$all=$1;
3660 ### $aux=~s#\n?($DELCMDOPEN|$DELCMDCLOSE)##g;
3661 ### $all."$aux$AUXCMD\n";}/sge;
3662 ### }
3663 ### # or protect \cite commands with \mbox
3664 ### if ($CITECMD) {
3665 ###### $delblock=~s/(\\($CITECMD)${extraspace}(?:\[$brat0\]${extraspace}){0,2}\{$pat_n\})(\s*)/\\mbox{$AUXCMD\n$1\n}$AUXCMD\n/msg ;
3666 ### $delblock=~s/(\\($CITECMD)${extraspace}(?:<$abrat0>${extraspace})?(?:\[$brat0\]${extraspace}){0,2}\{$pat_n\})(\s*)/\\mbox{$AUXCMD\n$1\n}$AUXCMD\n/msg ;
3667 ### }
3668 # if MBOXINLINEMATH is set, protect inlined math environments with an extra mbox
3669
3670 if ($MBOXINLINEMATH) {
3671 # note additional \newline after command is omitted from output if right at the end of deleted block (otherwise a spurious empty line is generated)
3672 $delblock =~ s/($math)(?:[\s\n]*)?/\\mbox{$AUXCMD\n$1\n}$AUXCMD\n/sg;
3673 }
3674 ###if ( defined($packages{"listings"} and $latexdiffpreamble =~ /\\RequirePackage(?:\[$brat_n\])?\{color\}/)) {
3675 ### # change included verbatim environments
3676 ### $delblock =~ s/\\DIFverb\{/\\DIFDIFdelverb\{/g;
3677 ### $delblock =~ s/\\DIFlstinline/\\DIFDIFdellstinline/g;
3678 ###}
3679 # Mark deleted verbatim commands
3680 $delblock =~
3681 s/(${DELCMDOPEN}\\DIF((?:verb\*?|lstinline(?:\[$brat_n\])?)\{([-\d]*?)\}\s*).*)$/%\n\\DIFDIFdel$2${AUXCMD}\n$1/gm;
3682 if ($CUSTOMDIFCMD) {
3683 ###$delblock =~ s/(${DELCMDOPEN}.*)\\($CUSTOMDIFCMD)((?:\[${brat_n}\])*?(?:\s*\{${pat_n}\})*)/"$1${DELCMDCLOSE}\\DEL$2". stripdelcmdopen($3) ." ${DELCMDOPEN}"/egms;
3684 ###$delblock =~ s/(${DELCMDOPEN}.*)\\($CUSTOMDIFCMD)/$1${DELCMDCLOSE}\\DEL$2/gm;
3685 # ($1 ? "${DELCMDOPEN}$1${DELCMDCLOSE}":"") : only add the DELCMDOPEN / DELCMDCLOSE pair if there are actually any commands in between, otherwise this is redundant
3686 $delblock =~
3687 s/${DELCMDOPEN}(.*?)\\($CUSTOMDIFCMD)((?:\[${brat_n}\])*?(?:\s*\{${pat_n}\})*)/($1 ? "${DELCMDOPEN}$1${DELCMDCLOSE}":"") ."\\DEL$2". stripdelcmdopen($3)/egs;
3688 # if there is a sequence of several commands in the same row only the first will be converted due to the need to be connected to the DELCMDOPEN. To mop these up, just add the DEL to the front of any remaining cmd's in the deleted block
3689 $delblock =~ s/\\($CUSTOMDIFCMD)/\\DEL$1/g; # this will also convert comments but I guess it does not matter much
3690 }
3691
3692 # splice in modified delblock
3693 substr( $_, $begin, $len ) = $delblock;
3694 pos = $begin + length($delblock);
3695 }
3696
3697 ### print STDERR "<<<$_>>>\n" if $debug;
3698
3699 # make the array modification in added blocks
3700 while (m/\\DIFaddbegin.*?\\DIFaddend/sg) {
3701 $len = length($&);
3702 $begin = pos($_) - $len;
3703 $addblock = $&;
3704 while ( $addblock =~ m/($math)(\s*)/sg ) {
3705 $len2 = length($&);
3706 $begin2 = pos($addblock) - $len2;
3707 $mathblock = "%\n\\mbox{$AUXCMD\n$1\n}$AUXCMD\n";
3708 next unless ( $mathblock =~ /ARRAYBLOCK/ or $mathblock =~ m/\{$ARRENV\}/ );
3709 substr( $addblock, $begin2, $len2 ) = $mathblock;
3710 pos($addblock) = $begin2 + length($mathblock);
3711 }
3712 # if MBOXINLINEMATH is set, protect inlined math environments with an extra mbox
3713 if ($MBOXINLINEMATH) {
3714 ##$addblock=~s/($math)/\\mbox{$AUXCMD\n$1\n}$AUXCMD\n/sg;
3715 $addblock =~ s/($math)(?:[\s\n]*)?/\\mbox{$AUXCMD\n$1\n}$AUXCMD\n/sg;
3716 }
3717 ###if ( defined($packages{"listings"} and $latexdiffpreamble =~ /\\RequirePackage(?:\[$brat0\])?\{color\}/)) {
3718 # mark added verbatim commands
3719 $addblock =~ s/\\DIFverb/\\DIFDIFaddverb/g;
3720 $addblock =~ s/\\DIFlstinline/\\DIFDIFaddlstinline/g;
3721 if ($CUSTOMDIFCMD) {
3722 $addblock =~ s/\\($CUSTOMDIFCMD)/\\ADD$1/g; # this will also convert comments but I guess it does not matter much
3723 }
3724 # markup the optional arguments of \item
3725 $addblock =~ s/(\\$ITEMCMD$extraspace(?:<$abrat0>)?$extraspace)\[($brat_n)\]/
3726 @itemargs=splitlatex(substr($2,0,length($2)));
3727 $itemarg="[".join("",marktags("","",$ADDOPEN,$ADDCLOSE,"","",$ADDCOMMENT,\@itemargs))."]";
3728 "$1$itemarg"/sge; # old substitution: $1\[$ADDOPEN$2$ADDCLOSE\]
3729 ###}
3730 # splice in modified addblock
3731 substr( $_, $begin, $len ) = $addblock;
3732 pos = $begin + length($addblock);
3733 }
3734
3735 # Go through whole text, and by counting list environment commands, find out when we are within a list environment.
3736 # Within those restore deleted \item commands
3737 @textparts = split /(?<!$DELCMDOPEN)(\\(?:begin|end)\{$LISTENV\})/;
3738 @liststack = ();
3739 @newtextparts = map {
3740 ### print STDERR ":::::::: $_\n";
3741 if ( ($listtype) = m/^\\begin\{($LISTENV)\}$/ ) {
3742 print STDERR "DEBUG: postprocess \\begin{$listtype}\n" if $debug;
3743 push @liststack, $listtype;
3744 } elsif ( ($listtype) = m/^\\end\{($LISTENV)\}$/ ) {
3745 print STDERR "DEBUG: postprocess \\end{$listtype}\n" if $debug;
3746 if ( scalar @liststack > 0 ) {
3747 $listlast = pop(@liststack);
3748 ( $listtype eq $listlast )
3749 or warn "Invalid nesting of list environments: $listlast environment closed by \\end{$listtype}.";
3750 } else {
3751 warn
3752 "WARNING: Invalid nesting of list environments: \\end{$listtype} encountered without matching \\begin{$listtype}.\n";
3753 }
3754 } else {
3755 print STDERR "DEBUG: postprocess \@liststack=(", join( ",", @liststack ), ")\n" if $debug;
3756 if ( scalar @liststack > 0 ) {
3757 # we are within a list environment and should replace all item commands
3758 $_ = restore_item_commands($_);
3759 }
3760 # else: we are outside a list environment and do not need to do anything
3761 }
3762 $_
3763 } @textparts; # end of map command
3764 # replace the main text with the modified version
3765 $_ = join( "", @newtextparts );
3766
3767
3768
3769 # Replace MATHMODE environments from step 1a above by the correct Math environment and remove unncessary pairings
3770
3771 if ( $mathmarkup == FINE ) {
3772 # look for AUXCMD math-mode pairs which have only comments (or empty lines between them), and remove the added commands
3773 # \begin{..} ... \end{..} pairs
3774 s/\\begin\{((?:$MATHENV)|(?:$MATHARRENV)|SQUAREBRACKET|MATHMODE)\}$AUXCMD\n((?:\s*%.[^\n]*\n)*)\\end\{\1\}$AUXCMD\n/$2/sg;
3775 # \end{..} .... \begin{..} pairs
3776 s/\\end\{((?:$MATHENV)|(?:$MATHARRENV)|SQUAREBRACKET|MATHMODE)\}$AUXCMD\n((?:\s*%.[^\n]*\n)*)\\begin\{\1\}$AUXCMD\n/$2/sg;
3777
3778 writedebugfile( $_, 'postprocess15' );
3779 # The next line is complicated. The negative look-ahead insertion makes sure that no \end{$MATHENV} (or other mathematical
3780 # environments) are between the \begin{$MATHENV} and \end{MATHMODE} commands. This is necessary as the minimal matching
3781 # is not globally minimal but only 'locally' (matching is beginning from the left side of the string)
3782 # [NB: Do not be tempted to prettify the expression with /x modified. It seems this is applied after strings are expanded so will ignore spaces in strings
3783 1 while
3784 s/(?<!$DELCMDOPEN)\\begin\{((?:$MATHENV)|(?:$MATHARRENV)|SQUAREBRACKET)}((?:${DELCMDOPEN}[^\n]*|.(?!(?:\\end\{(?:(?:$MATHENV)|(?:$MATHARRENV)|SQUAREBRACKET)}|\\begin\{MATHMODE})))*?)\\end\{MATHMODE}/\\begin{$1}$2\\end{$1}/s;
3785 writedebugfile( $_, 'postprocess16' );
3786 1 while
3787 s/\\begin\{MATHMODE}((?:.(?!\\end\{MATHMODE}))*?)(?<!$DELCMDOPEN)\\end\{((?:$MATHENV)|(?:$MATHARRENV)|SQUAREBRACKET)}/\\begin{$2}$1\\end{$2}/s;
3788 # convert remaining \begin{MATHMODE} \end{MATHMODE} (and not containing & or \\ )into MATHREPL environments
3789 s/\\begin\{MATHMODE\}((?:(.(?!(?<!\\)\&|\\\\))*)?)\\end\{MATHMODE\}/\\begin{$MATHREPL}$1\\end{$MATHREPL}/sg;
3790 # others into MATHARRREPL
3791 s/\\begin\{MATHMODE\}(.*?)\\end\{MATHMODE\}/\\begin{$MATHARRREPL}$1\\end{$MATHARRREPL}/sg;
3792 # Final cleanup of all equation environments: Sometimes I end up with %DIFDELCMD < \PAR lines, which I need to make sure do not get expanded into
3793 # actual empty lines within equation environments (later part)
3794 while (m/\\begin\{((?:$MATHENV|$MATHARRENV|SQUAREBRACKET)\*?)}.*?(?<!\%DIFDELCMD < )\\end\{\1}/sg) {
3795 $len = length($&);
3796 $begin = pos($_) - $len;
3797 $eqblock = $&;
3798 $eqblock =~ s/(%DIFDELCMD < )([^\n]*?)\\PAR\n/$1$2\n$1\n/sg;
3799 # splice in modified delblock
3800 print STDERR "DEBUG EQBLOCK: |$eqblock|\n\n" if $debug;
3801 substr( $_, $begin, $len ) = $eqblock;
3802 pos = $begin + length($eqblock);
3803 }
3804 } else {
3805 # math modes OFF,WHOLE,COARSE: Convert \MATHBLOCKmath{..} commands back to environments
3806 # with optionl argument to MATHBLOCK, e.g \MATHBLOCKalignat[{3}]{ ...}
3807 s/\\MATHBLOCK($MATHENV|$MATHARRENV\*?|SQUAREBRACKET)\[($brat0)\]\{($pat_n)\}/\\begin{$1}$2$3\\end{$1}/sg;
3808 # without optional argument e.g \MATHBLOCKalign{ ...}
3809 s/\\MATHBLOCK($MATHENV|$MATHARRENV\*?|SQUAREBRACKET)\{($pat_n)\}/\\begin{$1}$2\\end{$1}/sg;
3810 # convert ARRAYBLOCK.. commands back to environments (1 while construct allows nesting)
3811 1 while s/\\ARRAYBLOCK($ARRENV)\{($pat_n)\}/\\begin{$1}$2\\end{$1}/sg;
3812 # get rid of the DIFANCHOR markers, first the delete comments, then everywhere
3813 s/%DIFDELCMD < \\DIFANCHOR(?:MATH|ARR)[BE] (?:\n%DIFDELCMD < )?%%%\n//g;
3814 s/\\DIFANCHOR(?:MATH|ARR)[BE] //g;
3815 }
3816 writedebugfile( $_, 'postprocess2' );
3817
3818 # Convert all PICTUREblock{..} commands back to the appropriate environments
3819 s/\\PICTUREBLOCK($PICTUREENV)\{($pat_n)\}/\\begin{$1}$2\\end{$1}/sg;
3820 #0.5: # Remove all mark up within picture environments
3821 # while ( m/\\begin\{($PICTUREENV)\}.*?\\end\{\1\}/sg ) {
3822 # $cnt=0;
3823 # $len=length($&);
3824 # $begin=pos($_) - $len;
3825 # $float=$&;
3826 # $float =~ s/\\DIFaddbegin //g;
3827 # $float =~ s/\\DIFaddend //g;
3828 # $float =~ s/\\DIFadd\{($pat_n)\}/$1/g;
3829 # $float =~ s/\\DIFdelbegin //g;
3830 # $float =~ s/\\DIFdelend //g;
3831 # $float =~ s/\\DIFdel\{($pat_n)\}//g;
3832 # $float =~ s/$DELCMDOPEN.*//g;
3833 # substr($_,$begin,$len)=$float;
3834 # pos = $begin + length($float);
3835 # }
3836 # Convert DIFadd, DIFdel, DIFFaddbegin , ... into varieties
3837 # within floats (currently recognised float environments: plate,table,figure
3838 # plus starred varieties).
3839 while (m/\\begin\{($FLOATENV)\}.*?\\end\{\1\}/sg) {
3840 $len = length($&);
3841 $begin = pos($_) - $len;
3842 $float = $&;
3843 $float =~ s/\\DIFaddbegin /\\DIFaddbeginFL /g;
3844 $float =~ s/\\DIFaddend /\\DIFaddendFL /g;
3845 $float =~ s/\\DIFadd\{/\\DIFaddFL{/g;
3846 $float =~ s/\\DIFdelbegin /\\DIFdelbeginFL /g;
3847 $float =~ s/\\DIFdelend /\\DIFdelendFL /g;
3848 $float =~ s/\\DIFdel\{/\\DIFdelFL{/g;
3849 substr( $_, $begin, $len ) = $float;
3850 pos = $begin + length($float);
3851 }
3852 ### former location of undo renaming of \begin and \end in comments
3853
3854 # remove empty DIFCMD < lines
3855 s/^\Q${DELCMDOPEN}\E\n//msg;
3856
3857 # Look for paired \DIFdel{word} and \DIFadd{anotherword} commands and
3858 # check if a letter level diff is preferable
3859
3860 #while ( m/\\DIFdelbegin \\DIFdel\{(${word})\}\\DIFdelend \\DIFaddbegin \\DIFadd\{(${word})\}\\DIFaddend/g) {
3861 while (m/\\DIFdelbegin \\DIFdel\{($word\s*)\}\\DIFdelend \\DIFaddbegin \\DIFadd\{(${word}\s*)\}\\DIFaddend/g) {
3862 $len = length($&);
3863 $begin = pos($_) - $len;
3864 ###my @oldletters = split( //, $1 );
3865 ###my @newletters = split( //, $2 );
3866 my $word1 = $1;
3867 my $word2 = $2;
3868 my @oldletters = ( $word1 =~ /($word_cj |[-\w\d*]|\\[\"\'\`~^][A-Za-z\*])/g );
3869 my @newletters = ( $word2 =~ /($word_cj |[-\w\d*]|\\[\"\'\`~^][A-Za-z\*])/g );
3870
3871 ###print STDERR "DEBUG: Word detection. Found \\DIFdel{$word1}\\DIFadd{$word2} at ",pos,". Split into oldletters: |".join("|",@oldletters)."| and newletters: |".join("|",@newletters)."|\n" ;
3872 my @lettersdiff = pass2( \@oldletters, \@newletters );
3873 ###print STDERR "DEBUG: Word detection. Found \\DIFdel{$1}\\DIFadd{$2} at ",pos,". Replaced with ".join("",@lettersdiff) . "\n" ;
3874 ###print STDERR "Grep count: ", (scalar grep { $_ =~ /\\DIF(del|add)begin/} @lettersdiff),"\n";
3875 if ( ( grep { $_ =~ /\\DIF(del|add)begin/ } @lettersdiff ) <= $MAXCHANGESLETTER ) {
3876 # only make the change if there are at most 2 changes (up to 2 additions or deletions, or one substitution)
3877 my $repl = join( "", @lettersdiff );
3878 # if the string ends with spaces, then add '{}' after the last command to ensure there are not ignored
3879 $repl =~ s/(?<=\\DIF(?:add|del)end) (\s+)$/\{\}$1/sg;
3880 ###print STDERR "DEBUG: Replacing with |$repl|\n";
3881 substr( $_, $begin, $len ) = $repl;
3882 pos = $begin + length($repl);
3883 }
3884 }
3885 # Expand hashes of verb and verbatim environments
3886 s/${DELCMDOPEN}\\($VERBATIMENV)\{([-\d]*?)\}/"${DELCMDOPEN}\\begin{${1}}".fromhash(\%verbhash,$2,$DELCMDOPEN)."${DELCMDOPEN}\\end{${1}}"/esg;
3887 # revert changes to verbatim environments for line diffs (and add code to mark up changes) (note negative look behind assertions to not leak out of DIFDELCMD comments)
3888 # Example:
3889 # < \begin{verbatim}
3890 # < %DIF < DIFVRB old verbatim line
3891 # < %DIF > DIFVRB new verbatim line
3892 # < \end{verbatim}
3893 # ---
3894 # > \DIFmodbegin
3895 # > \begin{verbatim}[alsolanguage=DIFcode]
3896 # > %DIF < old verbatim line
3897 # > %DIF > new verbatim line
3898 # > \end{verbatim}
3899 # > \DIFmodend
3900 s/(?<!$DELCMDOPEN)\\begin\{($VERBATIMLINEENV)\}(.*?)(?<!$DELCMDOPEN)\\end\{\1\}/"". reverselinecomment($1, $2) .""/esg;
3901 # # we do the same for deleted environments but additionally reinstate the framing commands
3902 # s/$DELCMDOPEN\\begin\{($VERBATIMLINEENV)\}$extraspace(?:\[$brat0\])?$DELCMDCLOSE(.*?)$DELCMDOPEN\\end\{\1\}$DELCMDCLOSE/"\\begin{$1}". reverselinecomment($2) . "\\end{$1}"/esg;
3903 ## s/$DELCMDOPEN\\begin\{($VERBATIMLINEENV)\}($extraspace(?:\[$brat0\])?\s*)(?:\n|$DELCMDOPEN)*$DELCMDCLOSE((?:\%$DELCOMMENT$VERBCOMMENT.*?\n)*)($DELCMDOPEN\\end\{\1\}(?:\n|\s|$DELCMDOPEN)*$DELCMDCLOSE)/"SUBSTITUTION: \\begin{$1}$2 INTERIOR: |$3| END: |$4|"/esg;
3904 s/ # Deleted \begin command of verbatim environment (Captures $1: whole deleted command, $2: environment, $3: optional arguments with white space
3905 (\Q$DELCMDOPEN\E\\begin\{($VERBATIMLINEENV)\}(\Q$extraspace\E(?:\[$brat_n\])?\s*)(?:\n|\Q$DELCMDOPEN\E)*\Q$DELCMDCLOSE\E)
3906 # Interior of deleted verbatim environment should consist entirely of delete DIFVRB comments, i.e. match only lines beginning with % DIF < DIFVRB
3907 # Captures: $4: all lines combined
3908 ((?:\%\Q$DELCOMMENT$VERBCOMMENT\E[^\n]*?\n)*)
3909 # Deleted \end command of verbatim environment. Note that the type is forced to match the opening. Captures: $5: Whole deleted environment (previous way this line was written: (\Q$DELCMDOPEN\E\\end\{\2\}(?:\n|\s|\Q$DELCMDOPEN\E)*\Q$DELCMDCLOSE\E)
3910 (\Q$DELCMDOPEN\E\\end\{\2\})
3911 / # Substitution part
3912 $1 # Leave expression as is
3913 . "$AUXCMD NEXT\n" # Mark the following line as an auxiliary command
3914 . "" # reinstate the original environment without options
3915 . reverselinecomment($2, "$3$4") # modify the body to change the markup; reverselinecomment parses for options
3916 . " $AUXCMD\n" # close the auxiliary environment
3917 . $5 # and again leave the original deleted closing environment as is
3918 /esgx; # Modifiers of substitution command
3919 writedebugfile( $_, 'postprocess2' );
3920 # where changes have occurred in verbatim environment, change verbatim to DIFverbatim to allow mark-up
3921 # (I use the presence of optional paramater to verbatim environment as the marker - normal verbatim
3922 # environment does not take optional arguments)
3923 s/(?<!$DELCMDOPEN)\\begin\{(verbatim[*]?)\}(\[$brat_n\].*?)\\end\{\1\}/\\begin{DIF$1}$2\\end{DIF$1}/sg;
3924
3925 s/\\($VERBATIMENV)\{([-\d]*?)\}/"\\begin{${1}}".fromhash(\%verbhash,$2)."\\end{${1}}"/esg;
3926
3927 # remove all \PAR tokens (taking care to properly keep commented out PAR's
3928 # from introducing uncommented newlines - next line)
3929 s/(%DIF < )([^\n]*?)\\PAR\n/$1$2\n$1\n/sg;
3930 # convert PAR commands which are on a line by themselves
3931 s/\n(\s*?)\\PAR\n/\n\n/sg;
3932 # convert remaining PAR commands (which are preceded by non-white space characters, usually "}" ($ADDCLOSE)
3933 s/\\PAR\n/\n\n/sg;
3934
3935 # package specific processing:
3936 if ( defined( $packages{"endfloat"} ) ) {
3937 #endfloat: make sure \begin{figure} and \end{figure} are always
3938 # on a line by themselves, similarly for table environment
3939 print STDERR "endfloat package detected.\n" if $verbose;
3940 # eliminate whitespace before and after
3941 s/^(\s*)(\\(?:end|begin)\{(?:figure|table)\})(\s*?)$/$2/mg;
3942 # split lines with remaining characters before float environment conmmand
3943 s/^([^%]+)(\\(?:begin|end)\{(?:figure|table)\})/$1\n$2/mg;
3944 # split lines with remaining characters after float environment conmmand
3945 s/^((?:[^%]+)\\(?:begin|end)\{(?:figure|table)\}(?:\[[a-zA-Z]+\])?)(.+)((?:%.*)?)$/$1\n$2$3/mg;
3946 }
3947
3948 # Remove empty auxiliary LISTENV (sometmes these are generated if list environment occurs within the argument of a deleted comment)
3949 # (slightly hacky but I could not see an easy way to see if in argument of another command when this extra markup is added)
3950 s/\\begin\{($LISTENV)\}$AUXCMD\n((?:\s*\%[^\n]*\n)*\n?)\\end\{\1\}$AUXCMD\n/$2\n/msg;
3951
3952 # Convert '\PERCENTAGE ' back into '\%' (the final question mark catches a special situation where due to a latter pre-processing step the ' ' becomes separated
3953 s/\\PERCENTAGE ?/\\%/g;
3954 # Convert '\DOLLAR ' back into '\$'
3955 s/\\DOLLAR /\\\$/g;
3956
3957 # undo renaming of the \begin and \end,{,} and dollars in comments
3958
3959 # although we only renamed $ in comments to DOLLARDIFF, we might have lost the % in unchanged verbatim blocks, so rename all
3960 s/DOLLARDIF/\$/g;
3961 # Convert \begin{SQUAREBRACKET} \end{SQUAREBRACKET} into \[ \]
3962 s/\\end\{SQUAREBRACKET\}/\\\]/sg;
3963 s/\\begin\{SQUAREBRACKET\}/\\\[/sg;
3964 # 4. Convert \begin{DOLLARDOLLAR} \end{DOLLARDOLLAR} into $$ $$
3965 s/\\begin\{DOLLARDOLLAR\}(.*?)\\end\{DOLLARDOLLAR\}/\$\$$1\$\$/sg;
3966 # 5. Convert \SUPERSCRIPTNB{n} into ^n and \SUPERSCRIPT{nn} into ^{nnn}
3967 1 while s/\\SUPERSCRIPT(\s*\{($pat_n)\})/^$1/g;
3968 # 1 while s/\\SUPERSCRIPTNB\{(\s*$pat0)\}/^$1/g ;
3969 1 while s/\\SUPERSCRIPTNB\{(\s*$pat_n)\}/^$1/g;
3970 # Convert \SUBSCRIPNB{n} into _n and \SUBCRIPT{nn} into _{nnn}
3971 1 while s/\\SUBSCRIPT(\s*\{($pat_n)\})/_$1/g;
3972 1 while s/\\SUBSCRIPTNB\{(\s*$pat_n)\}/_$1/g;
3973 # Convert \SQRT{n} into \sqrt{n} and \SQRTNB{nn} into \sqrt nn
3974 1 while s/\\SQRT(\s*\{($pat_n)\})/\\sqrt$1/g;
3975 1 while s/\\SQRTNB\{(\s*$pat_n)\}/\\sqrt$1/g;
3976
3977
3978 # on converting back I don't need to assume these are in comments
3979 # (at this point in the code verbatim environments have already been converted from comments into their proper form
3980 # do only converting these auxiliary commands in comments does not work.
3981 1 while s/\\CCARET /^/g;
3982 1 while s/\\CUNDERSCORE /_/g;
3983 1 while s/\\CFRAC /\\frac/g;
3984 1 while s/\\CSQRT /\\sqrt/g;
3985 1 while s/\\CRIGHTBRACE /}/g;
3986 1 while s/\\CLEFTBRACE /{/g;
3987
3988 # Change \QLEFTBRACE, \QRIGHTBRACE to \{,\}
3989 s/\\QLEFTBRACE /\\\{/sg;
3990 s/\\QRIGHTBRACE /\\\}/sg;
3991 s/\\AMPERSAND /\\&/sg;
3992 # Highlight added inline verbatim commands if possible
3993 if ( $latexdiffpreamble =~ /\\RequirePackage(?:\[$brat_n\])?\{color\}/ ) {
3994 # wrap added verb commands with color commands
3995 s/\\DIFDIFadd((?:verb\*?|lstinline(?:\[$brat_n\])?)\{[-\d]*?\}[\s\n]*)/\{\\color{blue}$AUXCMD\n\\DIF$1%\n\}$AUXCMD\n/sg;
3996 s/\\DIFDIFdel((?:verb\*?|lstinline(?:\[$brat_n\])?)\{[-\d]*?\}[\s\n]*$AUXCMD)/\{\\color{red}${AUXCMD}\n\\DIF$1\n\}${AUXCMD}/sg;
3997 } else {
3998 # currently if colour markup is not used just remove the added mark
3999 s/\\DIFDIFadd(verb\*?|lstinline)/\\DIF$1/sg;
4000 s/\\DIFDIFdel((?:verb\*?|lstinline(?:\[$brat_n\])?)\{[-\d]*?\}[\s\n]*$AUXCMD\n)//sg;
4001 }
4002 # expand \verb and friends inline arguments
4003 s/\\DIF((?:DIFadd|DIFdel)?(?:verb\*?|lstinline(?:\[$brat_n\])?))\{([-\d]*?)\}/"\\${1}". fromhash(\%verbhash,$2)/esg;
4004 # add basicstyle color{blue} to added lstinline commands
4005 # finally add the comment to the ones not having an optional argument before
4006 ###s/\\DIFaddlstinline(?!\[)/\\lstinline\n[basicstyle=\\color{blue}]$AUXCMD\n/g;
4007
4008 }
4009 return;
4010 }
4011
4012 # $out = restore_item_commands($listenviron)
4013 # short helper function for post-process, which restores deleted \item commands in its argument (as DIFAUXCMDs)
4014 sub restore_item_commands {
4015 my ($string) = @_;
4016 my ( $itemarg, @itemargs );
4017 $string =~
4018 s/(\%DIFDELCMD < \s*(\\$ITEMCMD$extraspace)((?:<$abrat0>)?$extraspace)((?:\[$brat_n\])?)\s*((?:${cmdoptseq}\s*?)*)(?:\n|$DELCMDCLOSE))/
4019 # if \item has an []argument, then mark up the argument as deleted)
4020 if (length($4)>0) {
4021 # use substr to exclude square brackets at end points
4022 @itemargs=splitlatex(substr($4,1,length($4)-2));
4023 $itemarg="[".join("",marktags("","",$DELOPEN,$DELCLOSE,$DELCMDOPEN,$DELCMDCLOSE,$DELCOMMENT,\@itemargs))."]";
4024 } else {
4025 $itemarg="";
4026 }
4027 "$1$2$3$itemarg$AUXCMD\n"; ###.((length($5)>0) ? "%DIFDELCMD $5 $DELCMDCLOSE\n" : "")
4028 /sge;
4029 return ($string);
4030 }
4031
4032 # @auxlines=preprocess_preamble($oldpreamble,$newpreamble);
4033 # pre-process preamble by looking for commands used in \maketitle (title, author, date etc commands)
4034 # the list of commands is defined in CONTEXT2CMD
4035 # if found then use a bodydiff to mark up content, and replace the corresponding commands
4036 # in both preambles by marked up version to 'fool' the linediff (such that only body is marked up).
4037 # A special case are e.g. author commands being added (or removed)
4038 # 1. If commands are added, then the entire content is marked up as new, but also the lines are marked as new in the linediff
4039 # 2. If commands are removed, then the linediff will mark the line as deleted. The program returns
4040 # with $auxlines a text to be appended at the end of the preamble, which shows the respective fields as deleted
4041 sub preprocess_preamble {
4042 my ( $oldpreambleref, $newpreambleref ) = ( \$_[0], \$_[1] );
4043 my @auxlines = ();
4044 # Remember to use $$oldpreambleref to refer to oldpreamble
4045 my ( $titlecmd, $titlecmdpat );
4046 my ( @oldtitlecommands, @newtitlecommands );
4047 my %oldhash = ();
4048 my %newhash = ();
4049 my ( $line, $cmd, $optarg, $arg, $optargnew, $optargold, $optargdiff, $argold, $argnew, $argdiff, $auxline );
4050
4051 my $warnmsgdetail = <<EOF ;
4052 This should not occur for standard styles, but can occur for some specific styles, document classes,
4053 e.g. journal house styles.
4054 Workaround: Use --replace-context2cmd option to specifically set those commands, which are not repeated.
4055 EOF
4056
4057 # resuse context2cmdlist to define these commands to look out for in preamble
4058 $titlecmd = "(?:" . join( "|", @CONTEXT2CMDLIST ) . ")";
4059 # as context2cmdlist is stored as regex, e.g. ((?-xism:^title$), we need to remove ^- fo
4060 # resue in a more complex regex
4061 $titlecmd =~ s/[\$\^]//g;
4062 # make sure to not match on comment lines:
4063 $titlecmdpat = qr/^(?:[^%\n]|\\%)*(\\($titlecmd)$extraspace(?:\[($brat_n)\])?(?:\{($pat_n)\}))/ms;
4064 ###print STDERR "DEBUG:",$titlecmdpat,"\n";
4065 @oldtitlecommands = ( $$oldpreambleref =~ m/$titlecmdpat/g );
4066 @newtitlecommands = ( $$newpreambleref =~ m/$titlecmdpat/g );
4067
4068
4069 while (@oldtitlecommands) {
4070 $line = shift @oldtitlecommands;
4071 $cmd = shift @oldtitlecommands;
4072 $optarg = shift @oldtitlecommands;
4073 $arg = shift @oldtitlecommands;
4074
4075 if ( defined( $oldhash{$cmd} ) ) {
4076 warn "WARNING: $cmd is used twice in preamble of old file. Reverting to pure line diff mode for preamble.\n";
4077 print STDERR $warnmsgdetail;
4078 return;
4079 }
4080 $oldhash{$cmd} = [ $line, $optarg, $arg ];
4081 }
4082 while (@newtitlecommands) {
4083 $line = shift @newtitlecommands;
4084 $cmd = shift @newtitlecommands;
4085 $optarg = shift @newtitlecommands;
4086 $arg = shift @newtitlecommands;
4087
4088 if ( defined( $newhash{$cmd} ) ) {
4089 warn "$cmd is used twice in preamble of new file. Reverting to pure line diff mode for preamble.\n";
4090 print STDERR $warnmsgdetail;
4091 return;
4092 }
4093 $newhash{$cmd} = [ $line, $optarg, $arg ];
4094 }
4095 foreach $cmd ( keys %newhash ) {
4096 if ( defined( $newhash{$cmd}->[1] ) ) {
4097 $optargnew = $newhash{$cmd}->[1];
4098 } else {
4099 $optargnew = "";
4100 }
4101 if ( defined( $oldhash{$cmd}->[1] ) ) {
4102 $optargold = $oldhash{$cmd}->[1];
4103 } else {
4104 $optargold = "";
4105 }
4106
4107 if ( defined( $oldhash{$cmd}->[2] ) ) {
4108 $argold = $oldhash{$cmd}->[2];
4109 } else {
4110 $argold = "";
4111 }
4112 $argnew = $newhash{$cmd}->[2];
4113 $argdiff = "{" . join( "", bodydiff( $argold, $argnew ) ) . "}";
4114 # Replace \RIGHTBRACE by }
4115 $argdiff =~ s/\\RIGHTBRACE/}/g;
4116
4117 if ( length $optargnew ) {
4118 $optargdiff = "[" . join( "", bodydiff( $optargold, $optargnew ) ) . "]";
4119 $optargdiff =~ s/\\DIFaddbegin /\\DIFaddbeginFL /g;
4120 $optargdiff =~ s/\\DIFaddend /\\DIFaddendFL /g;
4121 $optargdiff =~ s/\\DIFadd\{/\\DIFaddFL{/g;
4122 $optargdiff =~ s/\\DIFdelbegin /\\DIFdelbeginFL /g;
4123 $optargdiff =~ s/\\DIFdelend /\\DIFdelendFL /g;
4124 $optargdiff =~ s/\\DIFdel\{/\\DIFdelFL{/g;
4125 } else {
4126 $optargdiff = "";
4127 }
4128 ### print STDERR "DEBUG s/\\Q$newhash{$cmd}->[0]\\E/\\$cmd$optargdiff$argdiff/s\n";
4129 # Note: \Q and \E force literal interpretation of what it between them but allow
4130 # variable interpolation, such that e.g. \title matches just that and not TAB-itle
4131 $$newpreambleref =~ s/\Q$newhash{$cmd}->[0]\E/\\$cmd$optargdiff$argdiff/s;
4132 # replace this in old preamble if necessary
4133 if ( defined( $oldhash{$cmd}->[0] ) ) {
4134 $$oldpreambleref =~ s/\Q$oldhash{$cmd}->[0]\E/\\$cmd$optargdiff$argdiff/s;
4135 }
4136 ### print STDERR "DEBUG NEW PRE ".$$newpreambleref."\n";
4137 }
4138
4139 foreach $cmd ( keys %oldhash ) {
4140 # if this has already been dealt with above can just skip
4141 next if defined( $newhash{$cmd} );
4142 $argold = $oldhash{$cmd}->[2];
4143 $argdiff = "{" . join( "", bodydiff( $argold, "" ) ) . "}";
4144 if ( defined( $oldhash{$cmd}->[1] ) ) {
4145 $optargold = $oldhash{$cmd}->[1];
4146 $optargdiff = "[" . join( "", bodydiff( $optargold, "" ) ) . "]";
4147 $optargdiff =~ s/\\DIFdelbegin /\\DIFdelbeginFL /g;
4148 $optargdiff =~ s/\\DIFdelend /\\DIFdelendFL /g;
4149 $optargdiff =~ s/\\DIFdel\{/\\DIFdelFL{/g;
4150 } else {
4151 $optargdiff = "";
4152 }
4153 $auxline = "\\$cmd$optargdiff$argdiff";
4154 $auxline =~ s/$/$AUXCMD/sg;
4155 push @auxlines, $auxline;
4156 }
4157 # add auxcmd comment to highlight added lines
4158 return (@auxlines);
4159 }
4160
4161 # @diffs=linediff(\@seq1, \@seq2)
4162 # mark up lines like this
4163 #%DIF mm-mmdnn
4164 #%< old deleted line(s)
4165 #%DIF -------
4166 #%DIF mmann-nn
4167 #new appended line %<
4168 #%DIF -------
4169 # Future extension: mark change explicitly
4170 # Assumes: traverse_sequence traverses deletions before insertions in changed sequences
4171 # all line numbers relative to line 0 (first line of real file)
4172 sub linediff {
4173 my $seq1 = shift;
4174 my $seq2 = shift;
4175
4176 my $block = [];
4177 my $retseq = [];
4178 my @begin = ( '', '', '' ); # dummy initialisation
4179 my $instring;
4180
4181 my $discard = sub {
4182 @begin = ( 'd', $_[0], $_[1] ) unless scalar @$block;
4183 push( @$block, "%DIF < " . $seq1->[ $_[0] ] );
4184 };
4185 my $add = sub {
4186 if ( !scalar @$block ) {
4187 @begin = ( 'a', $_[0], $_[1] );
4188 } elsif ( $begin[0] eq 'd' ) {
4189 $begin[0] = 'c';
4190 $begin[2] = $_[1];
4191 push( @$block, "%DIF -------" );
4192 }
4193 push( @$block, $seq2->[ $_[1] ] . " %DIF > " );
4194 };
4195 my $match = sub {
4196 if ( scalar @$block ) {
4197 if ( $begin[0] eq 'd' && $begin[1] != $_[0] - 1 ) {
4198 $instring = sprintf "%%DIF %d-%dd%d", $begin[1], $_[0] - 1, $begin[2];
4199 } elsif ( $begin[0] eq 'a' && $begin[2] != $_[1] - 1 ) {
4200 $instring = sprintf "%%DIF %da%d-%d", $begin[1], $begin[2], $_[1] - 1;
4201 } elsif ( $begin[0] eq 'c' ) {
4202 $instring = sprintf "%%DIF %sc%s",
4203 ( $begin[1] == $_[0] - 1 ) ? "$begin[1]" : $begin[1] . "-" . ( $_[0] - 1 ),
4204 ( $begin[2] == $_[1] - 1 ) ? "$begin[2]" : $begin[2] . "-" . ( $_[1] - 1 );
4205 } else {
4206 $instring = sprintf "%%DIF %d%s%d", $begin[1], $begin[0], $begin[2];
4207 }
4208 push @$retseq, $instring, @$block, "%DIF -------";
4209 $block = [];
4210 }
4211 push @$retseq, $seq2->[ $_[1] ];
4212 };
4213 # key function: remove multiple spaces (such that insertion or deletion of redundant white space is not reported)
4214 my $keyfunc = sub { join( " ", split( " ", shift() ) ) };
4215
4216 traverse_sequences( $seq1, $seq2, { MATCH => $match, DISCARD_A => $discard, DISCARD_B => $add }, $keyfunc );
4217 push @$retseq, @$block if scalar @$block;
4218
4219 return wantarray ? @$retseq : $retseq;
4220 }
4221
4222 # init_regex_arr_data(\@array,"TOKEN INIT")
4223 # scans DATA file handel for line "%% TOKEN INIT" line
4224 # then appends each line not beginning with % into array (as a quoted regex)
4225 # This is used for command lists and configuration variables, but the processing is slightly
4226 # different:
4227 # For lists, the regular expression is extended to include beginning (^) and end ($) markers, to require full-string matching
4228 # For configuration variables (and all others), simply an unadorned list is copied
4229 sub init_regex_arr_data {
4230 my ( $arr, $token ) = @_;
4231 my $copy = 0;
4232 my ($mode);
4233 if ( $token =~ m/COMMANDS/ ) {
4234 $mode = 0; # Reading command list
4235 } else {
4236 $mode = 1; # Reading configuration variables
4237 }
4238
4239 while (<DATA>) {
4240 if (m/^%%BEGIN $token\s*$/) {
4241 $copy = 1;
4242 next;
4243 } elsif (m/^%%END $token\s*$/) {
4244 last;
4245 }
4246 chomp;
4247 if ( $mode == 0 ) {
4248 # print STDERR "DEBUG init_regex_arr_data regex >$_<\n" if ($debug && $copy);
4249 push( @$arr, qr/^$_$/ ) if ( $copy && !/^%/ );
4250 } elsif ( $mode == 1 ) {
4251 push( @$arr, "$_" ) if ( $copy && !/^%/ );
4252 }
4253 }
4254 seek DATA, 0, 0; # rewind DATA handle to file begin
4255 }
4256
4257 # init_regex_arr_ext(\@array,$arg)
4258 # appends array with regular expressions.
4259 # if arg is a file name, then read in list of regular expressions from that file
4260 # (one expression per line)
4261 # Otherwise treat arg as a comma separated list of regular expressions
4262 sub init_regex_arr_ext {
4263 my ( $arr, $arg ) = @_;
4264 if ( -f $arg ) {
4265 init_regex_arr_file( $arr, $arg );
4266 } else {
4267 init_regex_arr_list( $arr, $arg );
4268 }
4269 }
4270
4271 # init_regex_arr_file(\@array,$fname)
4272 # appends array with regular expressions.
4273 # Read in list of regular expressions from $fname
4274 # (one expression per line)
4275 sub init_regex_arr_file {
4276 my ( $arr, $fname ) = @_;
4277 open( FILE, "$fname" ) or die("Couldn't open $fname: $!");
4278 while (<FILE>) {
4279 chomp;
4280 next if /^\s*#/ || /^\s*%/ || /^\s*$/;
4281 push( @$arr, qr/^$_$/ );
4282 }
4283 close(FILE);
4284 }
4285
4286 # init_regex_arr_list(\@array,$arg)
4287 # appends array with regular expressions.
4288 # read from comma separated list of regular expressions ($arg)
4289 sub init_regex_arr_list {
4290 my ( $arr, $arg ) = @_;
4291 my $regex;
4292 ### print STDERR "DEBUG init_regex_arr_list arg >$arg<\n" if $debug;
4293 foreach $regex ( split( qr/(?<!\\),/, $arg ) ) {
4294 $regex =~ s/\\,/,/g;
4295 print STDERR "DEBUG init_regex_arr_list regex >$regex<\n" if $debug;
4296 push( @$arr, qr/^$regex$/ );
4297 }
4298 }
4299
4300 #exetime() returns time since last execution of this command
4301 #exetime(1) resets this time
4302 my $lasttime = -1; # global variable for persistence
4303
4304 sub exetime {
4305 my $reset = 0;
4306 my $retval;
4307 if ( ( scalar @_ ) >= 1 ) {
4308 $reset = shift;
4309 }
4310 if ($reset) {
4311 $lasttime = times();
4312 } else {
4313 $retval = times() - $lasttime;
4314 $lasttime = $lasttime + $retval;
4315 return ($retval);
4316 }
4317 }
4318
4319 sub usage {
4320 print STDERR <<"EOF";
4321 Usage: $0 [options] old.tex new.tex > diff.tex
4322
4323 Compares two latex files and writes tex code to stdout, which has the same format as new.tex but
4324 has all changes relative to old.tex marked up or commented. Note that old.tex and new.tex need to
4325 be real files (not pipes or similar) as they are opened twice.
4326
4327 --type=markupstyle
4328 -t markupstyle Add code to preamble for selected markup style
4329 Available styles: UNDERLINE CTRADITIONAL TRADITIONAL CFONT FONTSTRIKE INVISIBLE
4330 CHANGEBAR CCHANGEBAR CULINECHBAR CFONTCHBAR BOLD PDFCOMMENT
4331 LUAUNDERLINE
4332 [ Default: UNDERLINE ]
4333
4334 --subtype=markstyle
4335 -s markstyle Add code to preamble for selected style for bracketing
4336 commands (e.g. to mark changes in margin)
4337 Available styles: SAFE MARGIN DVIPSCOL COLOR ZLABEL ONLYCHANGEDPAGE (LABEL)*
4338 [ Default: SAFE ]
4339 * LABEL subtype is deprecated
4340
4341 --floattype=markstyle
4342 -f markstyle Add code to preamble for selected style which
4343 replace standard marking and markup commands within floats
4344 (e.g., marginal remarks cause an error within floats
4345 so marginal marking can be disabled thus)
4346 Available styles: FLOATSAFE IDENTICAL
4347 [ Default: FLOATSAFE ]
4348
4349 --encoding=enc
4350 -e enc Specify encoding of old.tex and new.tex. Typical encodings are
4351 ascii, utf8, latin1, latin9. A list of available encodings can be
4352 obtained by executing
4353 perl -MEncode -e 'print join ("\\n",Encode->encodings( ":all" )) ;'
4354 [Default encoding is utf8 unless the first few lines of the preamble contain
4355 an invocation "\\usepackage[..]{inputenc} in which case the
4356 encoding chosen by this command is asssumed. Note that ASCII (standard
4357 latex) is a subset of utf8]
4358
4359 --preamble=file
4360 -p file Insert file at end of preamble instead of auto-generating
4361 preamble. The preamble must define the following commands
4362 \\DIFaddbegin,\\DIFaddend,\\DIFadd{..},
4363 \\DIFdelbegin,\\DIFdelend,\\DIFdel{..},
4364 and varieties for use within floats
4365 \\DIFaddbeginFL,\\DIFaddendFL,\\DIFaddFL{..},
4366 \\DIFdelbeginFL,\\DIFdelendFL,\\DIFdelFL{..}
4367 (If this option is set -t, -s, and -f options
4368 are ignored.)
4369
4370 --exclude-safecmd=exclude-file
4371 --exclude-safecmd="cmd1,cmd2,..."
4372 -A exclude-file
4373 --replace-safecmd=replace-file
4374 --append-safecmd=append-file
4375 --append-safecmd="cmd1,cmd2,..."
4376 -a append-file Exclude from, replace or append to the list of regex
4377 matching commands which are safe to use within the
4378 scope of a \\DIFadd or \\DIFdel command. The file must contain
4379 one Perl-RegEx per line (Comment lines beginning with # or % are
4380 ignored). A literal comma within the comma-separated list must be
4381 escaped thus "\\,", Note that the RegEx needs to match the whole of
4382 the token, i.e., /^regex\$/ is implied and that the initial
4383 "\\" of the command is not included. The --exclude-safecmd
4384 and --append-safecmd options can be combined with the --replace-safecmd
4385 option and can be used repeatedly to add cumulatively to the lists.
4386
4387 --exclude-textcmd=exclude-file
4388 --exclude-textcmd="cmd1,cmd2,..."
4389 -X exclude-file
4390 --replace-textcmd=replace-file
4391 --append-textcmd=append-file
4392 --append-textcmd="cmd1,cmd2,..."
4393 -x append-file Exclude from, replace or append to the list of regex
4394 matching commands whose last argument is text. See
4395 entry for --exclude-safecmd directly above for further details.
4396
4397 --replace-context1cmd=replace-file
4398 --append-context1cmd=append-file
4399 --append-context1cmd="cmd1,cmd2,..."
4400 Replace or append to the list of regex matching commands
4401 whose last argument is text but which require a particular
4402 context to work, e.g. \\caption will only work within a figure
4403 or table. These commands behave like text commands, except when
4404 they occur in a deleted section, when they are disabled, but their
4405 argument is shown as deleted text.
4406
4407 --replace-context2cmd=replace-file
4408 --append-context2cmd=append-file
4409 --append-context2cmd="cmd1,cmd2,..."
4410 As corresponding commands for context1. The only difference is that
4411 context2 commands are completely disabled in deleted sections, including
4412 their arguments.
4413 context2 commands are also the only commands in the preamble, whose argument will
4414 be processed in word-by-word mode (which only works, if they occur no more than
4415 once in the preamble).
4416
4417 --exclude-mboxsafecmd=exclude-file
4418 --exclude-mboxsafecmd="cmd1,cmd2,..."
4419 --append-mboxsafecmd=append-file
4420 --append-mboxsafecmd="cmd1,cmd2,..."
4421 Define safe commands, which additionally need to be protected by encapsulating
4422 in an \\mbox{..}. This is sometimes needed to get around incompatibilities
4423 between external packages and the ulem package, which is used for highlighting
4424 in the default style UNDERLINE as well as CULINECHBAR CFONTSTRIKE
4425
4426
4427
4428 --config var1=val1,var2=val2,...
4429 -c var1=val1,.. Set configuration variables.
4430 -c configfile Available variables:
4431 ARRENV (RegEx)
4432 COUNTERCMD (RegEx)
4433 FLOATENV (RegEx)
4434 ITEMCMD (RegEx)
4435 LISTENV (RegEx)
4436 MATHARRENV (RegEx)
4437 MATHENV (RegEx)
4438 MATHREPL (String)
4439 MAXCHANGESLETTER (Integer)
4440 MINWORDSBLOCK (Integer)
4441 PICTUREENV (RegEx)
4442 SCALEDELGRAPHICS (Float)
4443 VERBATIMENV (RegEx)
4444 VERBATIMLINEENV (RegEx)
4445 CUSTOMDIFCMD (RegEx)
4446 This option can be repeated.
4447
4448 --add-to-config varenv1=pattern1,varenv2=pattern2
4449 For configuration variables containing a regular expression (essentially those ending
4450 in ENV, and COUNTERCMD) this provides an alternative way to modify the configuration
4451 variables. Instead of setting the complete pattern, with this option it is possible to add an
4452 alternative pattern. varenv must be one of the variables listed above that take a regular
4453 expression as argument, and pattern is any regular expression (which might need to be
4454 protected from the shell by quotation). Several patterns can be added at once by using semi-colons
4455 to separate them, e.g. --add-to-config "LISTENV=myitemize;myenumerate,COUNTERCMD=endnote"
4456
4457 --packages=pkg1,pkg2,..
4458 Tell latexdiff that .tex file is processed with the packages in list
4459 loaded. This is normally not necessary if the .tex file includes the
4460 preamble, as the preamble is automatically scanned for \\usepackage commands.
4461 Use of the --packages option disables automatic scanning, so if for any
4462 reason package specific parsing needs to be switched off, use --packages=none.
4463 The following packages trigger special behaviour:
4464 endfloat hyperref amsmath apacite siunitx cleveref glossaries mhchem chemformula/chemmacros
4465 biblatex
4466 [ Default: scan the preamble for \\usepackage commands to determine
4467 loaded packages.]
4468
4469 --show-preamble Print generated or included preamble commands to stdout.
4470
4471 --show-safecmd Print list of regex matching and excluding safe commands.
4472
4473 --show-textcmd Print list of regex matching and excluding commands with text argument.
4474
4475 --show-config Show values of configuration variables
4476
4477 --show-all Show all of the above
4478
4479 NB For all --show commands, no old.tex or new.tex file needs to be given, and no
4480 differencing takes place.
4481
4482 Other configuration options:
4483
4484 --allow-spaces Allow spaces between bracketed or braced arguments to commands
4485 [Default requires arguments to directly follow each other without
4486 intervening spaces]
4487
4488 --math-markup=level Determine granularity of markup in displayed math environments:
4489 Possible values for level are (both numerical and text labels are acceptable):
4490 off or 0: suppress markup for math environments. Deleted equations will not
4491 appear in diff file. This mode can be used if all the other modes
4492 cause invalid latex code.
4493 whole or 1: Differencing on the level of whole equations. Even trivial changes
4494 to equations cause the whole equation to be marked changed. This
4495 mode can be used if processing in coarse or fine mode results in
4496 invalid latex code.
4497 coarse or 2: Detect changes within equations marked up with a coarse
4498 granularity; changes in equation type (e.g.displaymath to equation)
4499 appear as a change to the complete equation. This mode is recommended
4500 for situations where the content and order of some equations are still
4501 being changed. [Default]
4502 fine or 3: Detect small change in equations and mark up and fine granularity.
4503 This mode is most suitable, if only minor changes to equations are
4504 expected, e.g. correction of typos.
4505
4506 --graphics-markup=level Change highlight style for graphics embedded with \\includegraphics commands
4507 Possible values for level:
4508 none,off or 0: no highlighting for figures
4509 new-only or 1: surround newly added or changed figures with a blue frame [Default]
4510 both or 2: highlight new figures with a blue frame and show deleted figures
4511 at reduced scale, and crossed out with a red diagonal cross. Use configuration
4512 variable SCALEDELGRAPHICS to set size of deleted figures.
4513 Note that changes to the optional parameters will make the figure appear as changed
4514 to latexdiff, and this figure will thus be highlighted.
4515 In some circumstances "Misplaced \\noalign" errors can occur if there are certain types
4516 of changes in tables. In this case please use option --graphics-markup=none as a
4517 work-around.
4518
4519 --no-del Suppress deleted text from the diff. It is similar in effect to the BOLD style,
4520 but the deleted text ist not just invisible in the output, it is also not included in the
4521 diff text file. This can be more robust than just making it invisible.
4522
4523 --disable-citation-markup
4524 --disable-auto-mbox Suppress citation markup and markup of other vulnerable commands in styles
4525 using ulem (UNDERLINE,FONTSTRIKE, CULINECHBAR)
4526 (the two options are identical and are simply aliases)
4527
4528 --enable-citation-markup
4529 --enforce-auto-mbox Protect citation commands and other vulnerable commands in changed sections
4530 with \\mbox command, i.e. use default behaviour for ulem package for other packages
4531 (the two options are identical and are simply aliases)
4532
4533
4534
4535 Miscellaneous options
4536
4537 --label=label
4538 -L label Sets the labels used to describe the old and new files. The first use
4539 of this option sets the label describing the old file and the second
4540 use of the option sets the label for the new file.
4541 [Default: use the filename and modification dates for the label]
4542
4543 --no-label Suppress inclusion of old and new file names as comment in output file
4544
4545 --visible-label Include old and new filenames (or labels set with --label option) as
4546 visible output
4547
4548 --flatten Replace \\input and \\include commands within body by the content
4549 of the files in their argument. If \\includeonly is present in the
4550 preamble, only those files are expanded into the document. However,
4551 no recursion is done, i.e. \\input and \\include commands within
4552 included sections are not expanded. The included files are assumed to
4553 be located in the same directories as the old and new master files,
4554 respectively, making it possible to organise files into old and new directories.
4555 --flatten is applied recursively, so inputted files can contain further
4556 \\input statements. Also handles files included by the import package
4557 (\\import and \\subimport), and \\subfile command.
4558
4559 --filter-script=filterscript Run files through this filterscript (full path preferred) before processing.
4560 The filterscript must take STDIN input and output to STDOUT.
4561 When coupled with --flatten, each file will be run through the filter as it is brought in.
4562
4563 --ignore-filter-stderr When running with --filter-script, STDERR from the script may cause readability issues.
4564 Turn this flag on to ignore STDERR from the filter script.
4565
4566 --driver=type Choose driver for changebar package (only relevant for styles using
4567 changebar: CCHANGEBAR CFONTCHBAR CULINECHBAR CHANGEBAR). Possible
4568 drivers are listed in changebar manual, e.g. pdftex,dvips,dvitops
4569 [Default: pdftex]
4570
4571 --help
4572 -h Show this help text.
4573
4574 --ignore-warnings Suppress warnings about inconsistencies in length between input
4575 and parsed strings and missing characters.
4576
4577 --verbose
4578 -V Output various status information to stderr during processing.
4579 Default is to work silently.
4580
4581 --version Show version number.
4582
4583 Internal options:
4584 These options are mostly for automated use by latexdiff-vc. They can be used directly, but
4585 the API should be considered less stable than for the other options.
4586
4587 --no-links Suppress generation of hyperreferences, used for minimal diffs
4588 (option --only-changes of latexdiff-vc).
4589
4590 Directives:
4591 Special comments in the latex source that modify latexdiff behaviour.
4592 In the new file, those directives can be used:
4593 %BEGIN DIFNOMRKUP
4594 %END DIFNOMRKUP
4595 Tell latexdiff to not mark up the enclosed text.
4596
4597 %BEGIN DIFADD
4598 %END DIFADD
4599 Tell latexdiff to mark up the enclosed text as added.
4600
4601 In the old file, those directives can be used:
4602 %BEGIN DIFDEL
4603 %END DIFDEL
4604 Tell latexdiff to mark up the enclosed text as deleted.
4605
4606 EOF
4607 exit 0;
4608 }
4609
4610 =head1 NAME
4611
4612 latexdiff - determine and markup differences between two latex files
4613
4614 =head1 SYNOPSIS
4615
4616 B<latexdiff> [ B<OPTIONS> ] F<old.tex> F<new.tex> > F<diff.tex>
4617
4618 =head1 DESCRIPTION
4619
4620 Briefly, I<latexdiff> is a utility program to aid in the management of
4621 revisions of latex documents. It compares two valid latex files, here
4622 called C<old.tex> and C<new.tex>, finds significant differences
4623 between them (i.e., ignoring the number of white spaces and position
4624 of line breaks), and adds special commands to highlight the
4625 differences. Where visual highlighting is not possible, e.g. for changes
4626 in the formatting, the differences are
4627 nevertheless marked up in the source. Note that old.tex and new.tex need to
4628 be real files (not pipes or similar) as they are opened twice (unless C<--encoding> option is used)
4629
4630 The program treats the preamble differently from the main document.
4631 Differences between the preambles are found using line-based
4632 differencing (similarly to the Unix diff command, but ignoring white
4633 spaces). A comment, "S<C<%DIF E<gt>>>" is appended to each added line, i.e. a
4634 line present in C<new.tex> but not in C<old.tex>. Discarded lines
4635 are deactivated by prepending "S<C<%DIF E<lt>>>". Changed blocks are preceded by
4636 comment lines giving information about line numbers in the original files. Where there are insignificant
4637 differences, the resulting file C<diff.tex> will be similar to
4638 C<new.tex>. At the end of the preamble, the definitions for I<latexdiff> markup commands are inserted.
4639 In differencing the main body of the text, I<latexdiff> attempts to
4640 satisfy the following guidelines (in order of priority):
4641
4642 =over 3
4643
4644 =item 1
4645
4646 If both C<old.tex> and C<new.tex> are valid LaTeX, then the resulting
4647 C<diff.tex> should also be valid LateX. (NB If a few plain TeX commands
4648 are used within C<old.tex> or C<new.tex> then C<diff.tex> is not
4649 guaranteed to work but usually will).
4650
4651 =item 2
4652
4653 Significant differences are determined on the level of
4654 individual words. All significant differences, including differences
4655 between comments should be clearly marked in the resulting source code
4656 C<diff.tex>.
4657
4658 =item 3
4659
4660 If a changed passage contains text or text-producing commands, then
4661 running C<diff.tex> through LateX should produce output where added
4662 and discarded passages are highlighted.
4663
4664 =item 4
4665
4666 Where there are insignificant differences, e.g. in the positioning of
4667 line breaks, C<diff.tex> should follow the formatting of C<new.tex>
4668
4669 =back
4670
4671 For differencing the same algorithm as I<diff> is used but words
4672 instead of lines are compared. An attempt is made to recognize
4673 blocks which are completely changed such that they can be marked up as a unit.
4674 Comments are differenced line by line
4675 but the number of spaces within comments is ignored. Commands including
4676 all their arguments are generally compared as one unit, i.e., no mark-up
4677 is inserted into the arguments of commands. However, for a selected
4678 number of commands (for example, C<\caption> and all sectioning
4679 commands) the last argument is known to be text. This text is
4680 split into words and differenced just as ordinary text (use options to
4681 show and change the list of text commands, see below). As the
4682 algorithm has no detailed knowledge of LaTeX, it assumes all pairs of
4683 curly braces immediately following a command (i.e. a sequence of
4684 letters beginning with a backslash) are arguments for that command.
4685 As a restriction to condition 1 above it is thus necessary to surround
4686 all arguments with curly braces, and to not insert
4687 extraneous spaces. For example, write
4688
4689 \section{\textem{This is an emphasized section title}}
4690
4691 and not
4692
4693 \section {\textem{This is an emphasized section title}}
4694
4695 or
4696
4697 \section\textem{This is an emphasized section title}
4698
4699 even though all varieties are the same to LaTeX (but see
4700 B<--allow-spaces> option which allows the second variety).
4701
4702 For environments whose content does not conform to standard LaTeX or
4703 where graphical markup does not make sense all markup commands can be
4704 removed by setting the PICTUREENV configuration variable, set by
4705 default to C<picture> and C<DIFnomarkup> environments; see B<--config>
4706 option). The latter environment (C<DIFnomarkup>) can be used to
4707 protect parts of the latex file where the markup results in illegal
4708 markup. You have to surround the offending passage in both the old and
4709 new file by C<\begin{DIFnomarkup}> and C<\end{DIFnomarkup}>. You must
4710 define the environment in the preambles of both old and new
4711 documents. I prefer to define it as a null-environment,
4712
4713 C<\newenvironment{DIFnomarkup}{}{}>
4714
4715 but the choice is yours. Any markup within the environment will be
4716 removed, and generally everything within the environment will just be
4717 taken from the new file.
4718
4719 It is also possible to difference files which do not have a preamble.
4720 In this case, the file is processed in the main document
4721 mode, but the definitions of the markup commands are not inserted.
4722
4723 All markup commands inserted by I<latexdiff> begin with "C<\DIF>". Added
4724 blocks containing words, commands or comments which are in C<new.tex>
4725 but not in C<old.tex> are marked by C<\DIFaddbegin> and C<\DIFaddend>.
4726 Discarded blocks are marked by C<\DIFdelbegin> and C<\DIFdelend>.
4727 Within added blocks all text is highlighted with C<\DIFadd> like this:
4728 C<\DIFadd{Added text block}>
4729 Selected `safe' commands can be contained in these text blocks as well
4730 (use options to show and change the list of safe commands, see below).
4731 All other commands as well as braces "{" and "}" are never put within
4732 the scope of C<\DIFadd>. Added comments are marked by prepending
4733 "S<C<%DIF E<gt> >>".
4734
4735 Within deleted blocks text is highlighted with C<\DIFdel>. Deleted
4736 comments are marked by prepending "S<C<%DIF E<lt> >>". Non-safe command
4737 and curly braces within deleted blocks are commented out with
4738 "S<C<%DIFDELCMD E<lt> >>".
4739
4740
4741
4742 =head1 OPTIONS
4743
4744 =head2 Preamble
4745
4746 The following options determine the visual markup style by adding the appropriate
4747 command definitions to the preamble. See the end of this section for a description of
4748 available styles.
4749
4750 =over 4
4751
4752 =item B<--type=markupstyle> or
4753 B<-t markupstyle>
4754
4755 Add code to preamble for selected markup style. This option defines
4756 C<\DIFadd> and C<\DIFdel> commands.
4757 Available styles:
4758
4759 C<UNDERLINE CTRADITIONAL TRADITIONAL CFONT FONTSTRIKE INVISIBLE
4760 CHANGEBAR CCHANGEBAR CULINECHBAR CFONTCHBAR BOLD PDFCOMMENT
4761 LUAUNDERLINE>
4762
4763 [ Default: C<UNDERLINE> ]
4764
4765 =item B<--subtype=markstyle> or
4766 B<-s markstyle>
4767
4768 Add code to preamble for selected style for bracketing
4769 commands (e.g. to mark changes in margin). This option defines
4770 C<\DIFaddbegin>, C<\DIFaddend>, C<\DIFdelbegin> and C<\DIFdelend> commands.
4771 Available styles: C<SAFE MARGIN COLOR DVIPSCOL ZLABEL ONLYCHANGEDPAGE (LABEL)*>
4772
4773 [ Default: C<SAFE> ]
4774 * Subtype C<LABEL> is deprecated
4775
4776 =item B<--floattype=markstyle> or
4777 B<-f markstyle>
4778
4779 Add code to preamble for selected style which
4780 replace standard marking and markup commands within floats
4781 (e.g., marginal remarks cause an error within floats
4782 so marginal marking can be disabled thus). This option defines all
4783 C<\DIF...FL> commands.
4784 Available styles: C<FLOATSAFE TRADITIONALSAFE IDENTICAL>
4785
4786 [ Default: C<FLOATSAFE> ]
4787
4788 =item B<--encoding=enc> or
4789 B<-e enc>
4790
4791 Specify encoding of old.tex and new.tex. Typical encodings are
4792 C<ascii>, C<utf8>, C<latin1>, C<latin9>. A list of available encodings can be
4793 obtained by executing
4794
4795 C<perl -MEncode -e 'print join ("\n",Encode->encodings( ":all" )) ;' >
4796
4797 If this option is used, then old.tex, new.tex are only opened once.
4798 [Default encoding is utf8 unless the first few lines of the preamble contain
4799 an invocation C<\usepackage[..]{inputenc}> in which case the
4800 encoding chosen by this command is asssumed. Note that ASCII (standard
4801 latex) is a subset of utf8]
4802
4803 =item B<--preamble=file> or
4804 B<-p file>
4805
4806 Insert file at end of preamble instead of generating
4807 preamble. The preamble must define the following commands
4808 C<\DIFaddbegin, \DIFaddend, \DIFadd{..},
4809 \DIFdelbegin,\DIFdelend,\DIFdel{..},>
4810 and varieties for use within floats
4811 C<\DIFaddbeginFL, \DIFaddendFL, \DIFaddFL{..},
4812 \DIFdelbeginFL, \DIFdelendFL, \DIFdelFL{..}>
4813 (If this option is set B<-t>, B<-s>, and B<-f> options
4814 are ignored.)
4815
4816 =item B<--packages=pkg1,pkg2,..>
4817
4818 Tell latexdiff that .tex file is processed with the packages in list
4819 loaded. This is normally not necessary if the .tex file includes the
4820 preamble, as the preamble is automatically scanned for C<\usepackage> commands.
4821 Use of the B<--packages> option disables automatic scanning, so if for any
4822 reason package specific parsing needs to be switched off, use B<--packages=none>.
4823 The following packages trigger special behaviour:
4824
4825 =over 8
4826
4827 =item C<endfloat>
4828
4829 Ensure that C<\begin{figure}> and C<\end{figure}> always appear by themselves on a line.
4830
4831 =item C<hyperref>
4832
4833 Change name of C<\DIFadd> and C<\DIFdel> commands to C<\DIFaddtex> and C<\DIFdeltex> and
4834 define new C<\DIFadd> and C<\DIFdel> commands, which provide a wrapper for these commands,
4835 using them for the text but not for the link defining command (where any markup would cause
4836 errors).
4837
4838 =item C<apacite>, C<biblatex>
4839
4840 Redefine the commands recognised as citation commands.
4841
4842 =item C<siunitx>
4843
4844 Treat C<\SI> as equivalent to citation commands (i.e. protect with C<\mbox> if markup style uses ulem package.
4845
4846 =item C<cleveref>
4847
4848 Treat C<\cref,\Cref>, etc as equivalent to citation commands (i.e. protect with C<\mbox> if markup style uses ulem package.
4849
4850 =item C<glossaries>
4851
4852 Define most of the glossaries commands as safe, protecting them with \mbox'es where needed
4853
4854 =item C<mhchem>
4855
4856 Treat C<\ce> as a safe command, i.e. it will be highlighted (note that C<\cee> will not be highlighted in equations as this leads to processing errors)
4857
4858 =item C<chemformula> or C<chemmacros>
4859
4860 Treat C<\ch> as a safe command outside equations, i.e. it will be highlighted (note that C<\ch> will not be highlighted in equations as this leads to processing errors)
4861
4862
4863 =back
4864
4865 [ Default: scan the preamble for C<\usepackage> commands to determine
4866 loaded packages. ]
4867
4868
4869 =back
4870
4871 =head2 Configuration
4872
4873 =over 4
4874
4875 =item B<--exclude-safecmd=exclude-file> or
4876 B<-A exclude-file> or B<--exclude-safecmd="cmd1,cmd2,...">
4877
4878 =item B<--replace-safecmd=replace-file>
4879
4880 =item B<--append-safecmd=append-file> or
4881 B<-a append-file> or B<--append-safecmd="cmd1,cmd2,...">
4882
4883 Exclude from, replace or append to the list of regular expressions (RegEx)
4884 matching commands which are safe to use within the
4885 scope of a C<\DIFadd> or C<\DIFdel> command. The file must contain
4886 one Perl-RegEx per line (Comment lines beginning with # or % are
4887 ignored). Note that the RegEx needs to match the whole of
4888 the token, i.e., /^regex$/ is implied and that the initial
4889 "\" of the command is not included.
4890 The B<--exclude-safecmd> and B<--append-safecmd> options can be combined with the -B<--replace-safecmd>
4891 option and can be used repeatedly to add cumulatively to the lists.
4892 B<--exclude-safecmd>
4893 and B<--append-safecmd> can also take a comma separated list as input. If a
4894 comma for one of the regex is required, escape it thus "\,". In most cases it
4895 will be necessary to protect the comma-separated list from the shell by putting
4896 it in quotation marks.
4897
4898 =item B<--exclude-textcmd=exclude-file> or
4899 B<-X exclude-file> or B<--exclude-textcmd="cmd1,cmd2,...">
4900
4901 =item B<--replace-textcmd=replace-file>
4902
4903 =item B<--append-textcmd=append-file> or
4904 B<-x append-file> or B<--append-textcmd="cmd1,cmd2,...">
4905
4906 Exclude from, replace or append to the list of regular expressions
4907 matching commands whose last argument is text. See
4908 entry for B<--exclude-safecmd> directly above for further details.
4909
4910
4911 =item B<--replace-context1cmd=replace-file>
4912
4913 =item B<--append-context1cmd=append-file> or
4914
4915 =item B<--append-context1cmd="cmd1,cmd2,...">
4916
4917 Replace or append to the list of regex matching commands
4918 whose last argument is text but which require a particular
4919 context to work, e.g. C<\caption> will only work within a figure
4920 or table. These commands behave like text commands, except when
4921 they occur in a deleted section, when they are disabled, but their
4922 argument is shown as deleted text.
4923
4924 =item B<--replace-context2cmd=replace-file>
4925
4926 =item B<--append-context2cmd=append-file> or
4927
4928 =item B<--append-context2cmd="cmd1,cmd2,...">
4929
4930 As corresponding commands for context1. The only difference is that
4931 context2 commands are completely disabled in deleted sections, including
4932 their arguments.
4933
4934 context2 commands are also the only commands in the preamble, whose argument will be processed in
4935 word-by-word mode (which only works, if they occur no more than once in the preamble). The algorithm currently cannot cope with repeated context2 commands in the preamble, as they occur e.g. for the C<\author> argument in some journal styles (not in the standard styles, though
4936 If such a repetition is detected, the whole preamble will be processed in line-by-line mode. In such a case, use C<--replace-context2cmd> option to just select the commands, which should be processed and are not used repeatedly in the preamble.
4937
4938
4939
4940 =item B<--exclude-mboxsafecmd=exclude-file> or B<--exclude-mboxsafecmd="cmd1,cmd2,...">
4941
4942 =item B<--append-mboxsafecmd=append-file> or B<--append-mboxsafecmd="cmd1,cmd2,...">
4943
4944 Define safe commands, which additionally need to be protected by encapsulating
4945 in an C<\mbox{..}>. This is sometimes needed to get around incompatibilities
4946 between external packages and the ulem package, which is used for highlighting
4947 in the default style UNDERLINE as well as CULINECHBAR CFONTSTRIKE
4948
4949
4950
4951
4952
4953 =item B<--config var1=val1,var2=val2,...> or B<-c var1=val1,..>
4954
4955 =item B<-c configfile>
4956
4957 Set configuration variables. The option can be repeated to set different
4958 variables (as an alternative to the comma-separated list).
4959 Available variables (see below for further explanations):
4960
4961 C<ARRENV> (RegEx)
4962
4963 C<COUNTERCMD> (RegEx)
4964
4965 C<CUSTODIFCMD> (RegEx)
4966
4967 C<FLOATENV> (RegEx)
4968
4969 C<ITEMCMD> (RegEx)
4970
4971 C<LISTENV> (RegEx)
4972
4973 C<MATHARRENV> (RegEx)
4974
4975 C<MATHENV> (RegEx)
4976
4977 C<MATHREPL> (String)
4978
4979 C<MAXCHANGESLETTER> (Integer)
4980
4981 C<MINWORDSBLOCK> (Integer)
4982
4983 C<PICTUREENV> (RegEx)
4984
4985 C<SCALEDELGRAPHICS> (Float)
4986
4987
4988 =item B<--add-to-config varenv1=pattern1,varenv2=pattern2,...>
4989
4990 For configuration variables, which are a regular expression (essentially those ending
4991 in ENV, COUNTERCMD and CUSTOMDIFCMD, see list above) this option provides an alternative way to modify the configuration
4992 variables. Instead of setting the complete pattern, with this option it is possible to add an
4993 alternative pattern. C<varenv> must be one of the variables listed above that take a regular
4994 expression as argument, and pattern is any regular expression (which might need to be
4995 protected from the shell by quotation). Several patterns can be added at once by using semi-colons
4996 to separate them, e.g. C<--add-to-config "LISTENV=myitemize;myenumerate,COUNTERCMD=endnote">
4997
4998
4999 =item B<--show-preamble>
5000
5001 Print generated or included preamble commands.
5002
5003 =item B<--show-safecmd>
5004
5005 Print list of RegEx matching and excluding safe commands.
5006
5007 =item B<--show-textcmd>
5008
5009 Print list of RegEx matching and excluding commands with text argument.
5010
5011 =item B<--show-config>
5012
5013 Show values of configuration variables.
5014
5015 =item B<--show-all>
5016
5017 Combine all --show commands.
5018
5019 NB For all --show commands, the behaviour is different dependent whether C<old.tex> or C<new.tex> files are specified. If they are not not then the initial setup is shown. If they are specified, then the full configuration is shown, which includes some additions of internal commands, and modifications based on what packages are present on the system, or are used in the .tex files. Either way, no differencing takes place.
5020
5021 =back
5022
5023 =head2 Other configuration options:
5024
5025 =over 4
5026
5027 =item B<--allow-spaces>
5028
5029 Allow spaces between bracketed or braced arguments to commands. Note
5030 that this option might have undesirable side effects (unrelated scope
5031 might get lumpeded with preceding commands) so should only be used if the
5032 default produces erroneous results. (Default requires arguments to
5033 directly follow each other without intervening spaces).
5034
5035 =item B<--math-markup=level>
5036
5037 Determine granularity of markup in displayed math environments:
5038 Possible values for level are (both numerical and text labels are acceptable):
5039
5040 C<off> or C<0>: suppress markup for math environments. Deleted equations will not
5041 appear in diff file. This mode can be used if all the other modes
5042 cause invalid latex code.
5043
5044 C<whole> or C<1>: Differencing on the level of whole equations. Even trivial changes
5045 to equations cause the whole equation to be marked changed. This
5046 mode can be used if processing in coarse or fine mode results in
5047 invalid latex code.
5048
5049 C<coarse> or C<2>: Detect changes within equations marked up with a coarse
5050 granularity; changes in equation type (e.g.displaymath to equation)
5051 appear as a change to the complete equation. This mode is recommended
5052 for situations where the content and order of some equations are still
5053 being changed. [Default]
5054
5055 C<fine> or C<3>: Detect small change in equations and mark up at fine granularity.
5056 This mode is most suitable, if only minor changes to equations are
5057 expected, e.g. correction of typos.
5058
5059 =item B<--graphics-markup=level>
5060
5061 Change highlight style for graphics embedded with C<\includegraphics> commands.
5062
5063 Possible values for level:
5064
5065 C<none>, C<off> or C<0>: no highlighting for figures
5066
5067 C<new-only> or C<1>: surround newly added or changed figures with a blue frame [Default if graphicx package loaded]
5068
5069 C<both> or C<2>: highlight new figures with a blue frame and show deleted figures at reduced
5070 scale, and crossed out with a red diagonal cross. Use configuration
5071 variable SCALEDELGRAPHICS to set size of deleted figures.
5072
5073 Note that changes to the optional parameters will make the figure appear as changed
5074 to latexdiff, and this figure will thus be highlighted.
5075
5076 In some circumstances "Misplaced \noalign" error can occur if there are certain types
5077 of changes in tables. In this case please use C<--graphics-markup=none> as a
5078 work-around.
5079
5080
5081 =item B<--no-del>
5082
5083 Suppress deleted text from the diff. It is similar in effect to the BOLD style,
5084 but the deleted text ist not just invisible in the output, it is also not included in the diff text file.
5085 This can be more robust than just making it invisible.
5086
5087 =item B<--disable-citation-markup> or B<--disable-auto-mbox>
5088
5089 Suppress citation markup and markup of other vulnerable commands in styles
5090 using ulem (UNDERLINE,FONTSTRIKE, CULINECHBAR)
5091 (the two options are identical and are simply aliases)
5092
5093 =item B<--enable-citation-markup> or B<--enforce-auto-mbox>
5094
5095 Protect citation commands and other vulnerable commands in changed sections
5096 with C<\mbox> command, i.e. use default behaviour for ulem package for other packages
5097 (the two options are identical and are simply aliases)
5098
5099 =back
5100
5101 =head2 Miscellaneous
5102
5103 =over 4
5104
5105 =item B<--verbose> or B<-V>
5106
5107 Output various status information to stderr during processing.
5108 Default is to work silently.
5109
5110 =item B<--driver=type>
5111
5112 Choose driver for changebar package (only relevant for styles using
5113 changebar: CCHANGEBAR CFONTCHBAR CULINECHBAR CHANGEBAR). Possible
5114 drivers are listed in changebar manual, e.g. pdftex,dvips,dvitops
5115 [Default: pdftex]
5116
5117 =item B<--ignore-warnings>
5118
5119 Suppress warnings about inconsistencies in length between input and
5120 parsed strings and missing characters. These warning messages are
5121 often related to non-standard latex or latex constructions with a
5122 syntax unknown to C<latexdiff> but the resulting difference argument
5123 is often fully functional anyway, particularly if the non-standard
5124 latex only occurs in parts of the text which have not changed.
5125
5126 =item B<--label=label> or
5127 B<-L label>
5128
5129 Sets the labels used to describe the old and new files. The first use
5130 of this option sets the label describing the old file and the second
5131 use of the option sets the label for the new file, i.e. set both
5132 labels like this C<-L labelold -L labelnew>.
5133 [Default: use the filename and modification dates for the label]
5134
5135 =item B<--no-label>
5136
5137 Suppress inclusion of old and new file names as comment in output file
5138
5139 =item B<--visible-label>
5140
5141 Include old and new filenames (or labels set with C<--label> option) as
5142 visible output.
5143
5144 =item B<--flatten>
5145
5146 Replace C<\input> and C<\include> commands within body by the content
5147 of the files in their argument. If C<\includeonly> is present in the
5148 preamble, only those files are expanded into the document. However,
5149 no recursion is done, i.e. C<\input> and C<\include> commands within
5150 included sections are not expanded. The included files are assumed to
5151 be located in the same directories as the old and new master files,
5152 respectively, making it possible to organise files into old and new directories.
5153 --flatten is applied recursively, so inputted files can contain further
5154 C<\input> statements. Also handles files included by the import package
5155 (C<\import> and C<\subimport>), and C<\subfile> command.
5156
5157 Use of this option might result in prohibitive processing times for
5158 larger documents, and the resulting difference document
5159 no longer reflects the structure of the input documents.
5160
5161 =item B<--filter-script=filterscript>
5162
5163 Run files through this filterscript (full path preferred) before processing.
5164 The filterscript must take STDIN input and output to STDOUT.
5165 When coupled with --flatten, each file will be run through the filter as it is brought in.
5166
5167 =item B<--ignore-filter-stderr>
5168
5169 When running with --filter-script, STDERR from the script may cause readability issues.
5170 Turn this flag on to ignore STDERR from the filter script.
5171
5172
5173
5174 =item B<--help> or
5175 B<-h>
5176
5177 Show help text
5178
5179 =item B<--version>
5180
5181 Show version number
5182
5183 =back
5184
5185
5186 =head2 Internal options
5187
5188 These options are mostly for automated use by latexdiff-vc. They can be used directly, but the API should be considered less stable than for the other options.
5189
5190 =over 4
5191
5192 =item B<--no-links>
5193
5194 Suppress generation of hyperreferences, used for minimal diffs (option --only-changes of latexdiff-vc)
5195
5196 =back
5197
5198
5199 =head2 Predefined styles
5200
5201 =head2 Major types
5202
5203 The major type determine the markup of plain text and some selected latex commands outside floats by defining the markup commands C<\DIFadd{...}> and C<\DIFdel{...}> .
5204
5205 =over 10
5206
5207 =item C<UNDERLINE>
5208
5209 Added text is wavy-underlined and blue, discarded text is struck out and red
5210 (Requires color and ulem packages). Overstriking does not work in displayed math equations such that deleted parts of equation are underlined, not struck out (this is a shortcoming inherent to the ulem package).
5211
5212 =item C<LUAUNDERLINE>
5213
5214 Added text is underlined and blue, discarded text is struck out and red
5215 (Requires lua-ul package + LuaLaTeX).
5216
5217 =item C<CTRADITIONAL>
5218
5219 Added text is blue and set in sans-serif, and a red footnote is created for each discarded
5220 piece of text. (Requires color package)
5221
5222 =item C<TRADITIONAL>
5223
5224 Like C<CTRADITIONAL> but without the use of color.
5225
5226 =item C<CFONT>
5227
5228 Added text is blue and set in sans-serif, and discarded text is red and very small size.
5229
5230 =item C<FONTSTRIKE>
5231
5232 Added tex is set in sans-serif, discarded text small and struck out
5233
5234 =item C<CCHANGEBAR>
5235
5236 Added text is blue, and discarded text is red. Additionally, the changed text is marked with a bar in the margin (Requires color and changebar packages).
5237
5238 =item C<CFONTCHBAR>
5239
5240 Like C<CFONT> but with additional changebars (Requires color and changebar packages).
5241
5242 =item C<CULINECHBAR>
5243
5244 Like C<UNDERLINE> but with additional changebars (Requires color, ulem and changebar packages).
5245
5246 =item C<CHANGEBAR>
5247
5248 No mark up of text, but mark margins with changebars (Requires changebar package).
5249
5250 =item C<INVISIBLE>
5251
5252 No visible markup (but generic markup commands will still be inserted.
5253
5254 =item C<BOLD>
5255
5256 Added text is set in bold face, discarded is not shown. (also see --no-del option for another possibility to hide deleted text)
5257
5258 =item C<PDFCOMMENT>
5259
5260 The pdfcomment package is used to underline new text, and mark deletions with a PDF comment. Note that this markup might appear differently or not at all based on the pdf viewer used. The viewer with best support for pdf markup is probably acroread. This style is only recommended if the number of differences is small.
5261
5262 =back
5263
5264 =head2 Subtypes
5265
5266 The subtype defines the commands that are inserted at the begin and end of added or discarded blocks, irrespectively of whether these blocks contain text or commands (Defined commands: C<\DIFaddbegin, \DIFaddend, \DIFdelbegin, \DIFdelend>)
5267
5268 =over 10
5269
5270 =item C<SAFE>
5271
5272 No additional markup (Recommended choice)
5273
5274 =item C<MARGIN>
5275
5276 Mark beginning and end of changed blocks with symbols in the margin nearby (using
5277 the standard C<\marginpar> command - note that this sometimes moves somewhat
5278 from the intended position.
5279
5280 =item C<COLOR>
5281
5282 An alternative way of marking added passages in blue, and deleted ones in red.
5283 (It is recommeneded to use instead the main types to effect colored markup,
5284 although in some cases coloring with dvipscol can be more complete, for example
5285 with citation commands).
5286
5287 =item C<DVIPSCOL>
5288
5289 An alternative way of marking added passages in blue, and deleted ones in red. Note
5290 that C<DVIPSCOL> only works with the dvips converter, e.g. not pdflatex.
5291 (it is recommeneded to use instead the main types to effect colored markup,
5292 although in some cases coloring with dvipscol can be more complete).
5293
5294
5295 =item C<ZLABEL>
5296
5297 can be used to highlight only changed pages, but requires post-processing. It is recommend to not call this option manually but use C<latexdiff-vc> with C<--only-changes> option. Alternatively, use the script given within preamble of diff files made using this style.
5298
5299 =item C<ONLYCHANGEDPAGE>
5300
5301 also highlights changed pages, without the need for post-processing, but might not work reliably if
5302 there is floating material (figures, tables).
5303
5304 =item C<LABEL>
5305
5306 is similar to C<ZLABEL>, but does not need the zref package and works less reliably (deprecated).
5307
5308 =back
5309
5310 =head2 Float Types
5311
5312 Some of the markup used in the main text might cause problems when used within
5313 floats (e.g. figures or tables). For this reason alternative versions of all
5314 markup commands are used within floats. The float type defines these alternative commands.
5315
5316 =over 10
5317
5318 =item C<FLOATSAFE>
5319
5320 Use identical markup for text as in the main body, but set all commands marking the begin and end of changed blocks to null-commands. You have to choose this float type if your subtype is C<MARGIN> as C<\marginpar> does not work properly within floats.
5321
5322 =item C<TRADITIONALSAFE>
5323
5324 Mark additions the same way as in the main text. Deleted environments are marked by angular brackets \[ and \] and the deleted text is set in scriptscript size. This float type should always be used with the C<TRADITIONAL> and C<CTRADITIONAL> markup types as the \footnote command does not work properly in floating environments.
5325
5326 =item C<IDENTICAL>
5327
5328 Make no difference between the main text and floats.
5329
5330 =back
5331
5332
5333 =head2 Configuration Variables
5334
5335 =over 10
5336
5337 =item C<ARRENV>
5338
5339 If a match to C<ARRENV> is found within an inline math environment within a deleted or added block, then the inlined math
5340 is surrounded by C<\mbox{>...C<}>. This is necessary as underlining does not work within inlined array environments.
5341
5342 [ Default: C<ARRENV>=S<C<(?:array|[pbvBV]matrix)> >
5343
5344 =item C<COUNTERCMD>
5345
5346 If a command in a deleted block which is also in the textcmd list matches C<COUNTERCMD> then an
5347 additional command C<\addtocounter{>F<cntcmd>C<}{-1}>, where F<cntcmd> is the matching command, is appended in the diff file such that the numbering in the diff file remains synchronized with the
5348 numbering in the new file.
5349
5350 [ Default: C<COUNTERCMD>=C<(?:footnote|part|section|subsection> ...
5351
5352 C<|subsubsection|paragraph|subparagraph)> ]
5353
5354 =item C<CUSTOMDIFCMD>
5355
5356 This option is for advanced users and allows definition of special versions of commands, which do not work as safe commands.
5357
5358 Commands in C<CUSTOMDIFCMD> that occur in added or deleted blocks will be given an ADD or DEL prefix.
5359 The prefixed versions of the command must be defined in the preamble, either by putting them
5360 in the preamble of at least the new file, or by creating a custom preamble file (Option --preamble).
5361 For example the command C<\blindtext> (from package blindtext) does not interact well with underlining, so that
5362 for the standard markup type, it is not satisfactory to define it as a safe command. Instead, a customised versions
5363 without underlining can be defined in the preamble:
5364
5365 C<\newcommand{\DELblindtext}{{\color{red}\blindtext}}>
5366
5367 C<\newcommand{\ADDblindtext}{{\color{blue}\blindtext}}>
5368
5369 and then latexdiff should be invoked with the option C<-c CUSTOMDIFCMD=blindtext>.
5370
5371 [ Default: none ]
5372
5373 =item C<FLOATENV>
5374
5375 Environments whose name matches the regular expression in C<FLOATENV> are
5376 considered floats. Within these environments, the I<latexdiff> markup commands
5377 are replaced by their FL variaties.
5378
5379 [ Default: S<C<(?:figure|table|plate)[\w\d*@]*> >]
5380
5381 =item C<ITEMCMD>
5382
5383 Commands representing new item line with list environments.
5384
5385 [ Default: \C<item> ]
5386
5387 =item C<LISTENV>
5388
5389 Environments whose name matches the regular expression in C<LISTENV> are list environments.
5390
5391 [ Default: S<C<(?:itemize|enumerate|description)> >]
5392
5393 =item C<MATHENV>,C<MATHREPL>
5394
5395 If both \begin and \end for a math environment (environment name matching C<MATHENV> or \[ and \])
5396 are within the same deleted block, they are replaced by a \begin and \end commands for C<MATHREPL>
5397 rather than being commented out.
5398
5399 [ Default: C<MATHENV>=S<C<(?:displaymath|equation)> >, C<MATHREPL>=S<C<displaymath> >]
5400
5401 =item C<MAXCHANGESLETTER>
5402 When latexdiff detects a replacement of a single word, it will attempt to identify the changes at letter level. If there are many changes, it is likely that the word was replaced wholesale, and the letter-level changes would be confusing rather than helpful. In this case, latexdiff will fall back to display the replacement at word level. The approach to distinguish both cases is to simply count the number of distinct additions and deletions (not the number of letter changed!), and only if they are less than or equal to MAXCHANGESLETTER the letter-level markup is used. Sensible values are 0, 1, or 2. 0 will disable the letter-level markup completely. 1 will only allow a single addition or deletion, e.g., for a typo correction or change singular/plural of a verb, but no substitution. 2 will allow one substitution (or two additions or deletions)---this will sometimes result in different words being marked up on letter level, e.g. they-> there will show deleted "y" and added "re", which is often not desirable.
5403
5404 [ Default: 1 ]
5405
5406 =item C<MINWORDSBLOCK>
5407
5408 Minimum number of tokens required to form an independent block. This value is
5409 used in the algorithm to detect changes of complete blocks by merging identical text parts of less than C<MINWORDSBLOCK> to the preceding added and discarded parts.
5410
5411 [ Default: 3 ]
5412
5413 =item C<PICTUREENV>
5414
5415 Within environments whose name matches the regular expression in C<PICTUREENV>
5416 all latexdiff markup is removed (in pathologic cases this might lead to
5417 inconsistent markup but this situation should be rare).
5418
5419 [ Default: S<C<(?:picture|DIFnomarkup)[\w\d*@]*> >]
5420
5421 =item C<SCALEDELGRAPHICS>
5422
5423 If C<--graphics-markup=both> is chosen, C<SCALEDELGRAPHICS> is the factor, by which deleted figures will be scaled (i.e. 0.5 implies they are shown at half linear size).
5424
5425 [ Default: 0.5 ]
5426
5427 =item C<VERBATIMENV>
5428
5429 RegEx describing environments like verbatim, whose contents should be taken verbatim. The content of these environments will not be processed in any way:
5430 deleted content is commented out, new content is not marked up
5431
5432 [ Default: S<C<comment> > ]
5433
5434 =item C<VERBATIMLINEENV>
5435
5436 RegEx describing environments like verbatim, whose contents should be taken verbatim. The content of environments described by VERBATIMLINEENV are compared in
5437 line mode, and changes are marked up using the listings package. The markup style is set based on the chosen mains markup type (Option -t), or on an analysis
5438 of the preamble.
5439 Note that "listings.sty" must be installed. If this file is not found the fallback solution is to
5440 treat VERBATIMLINEENV environments treated exactly the same way as VERBATIMENV environments.
5441
5442 [ Default: S<C<(?:verbatim[*]?|lstlisting> > ]
5443
5444 =back
5445
5446 =head1 DIRECTIVES
5447
5448 Sometimes, the output C<latexdiff> produces is not satisfactory or
5449 some complicated constructions even lead to difference tex file that
5450 leads to error. It is possible to give
5451 latexdiff some hints to control the markup by placing some special
5452 comments, termed I<directives> into the tex file. Directives mark
5453 blocks by paired C<BEGIN> and C<END> directives. It is important that
5454 the directives are written exactly as specified below,i.e., all
5455 letters need to be capitalised and there has to be exactly one space
5456 between BEGIN/END and the block type. However, after the directive
5457 arbitrary comments can be added. Nesting of blocks or overlapping
5458 blocks are not parsed correctly and will cause undefined behaviour.
5459 Blocks can be spanning across scope boundaries; they can also be used in the last argument of text commands.
5460 If they appear in the arguments of other commands, then latexdiff will assume they were placed before or after
5461 the command; it is best to avoid this, though.
5462
5463 =over 10
5464
5465 =item C<DIFADD> block
5466
5467 ...
5468 %BEGIN DIFADD
5469 ...
5470 %END DIFADD
5471 ...
5472
5473 Everything enclosed between the C<%BEGIN DIFADD> and C<%END DIFADD> directives will be treated as atomistic addition to the
5474 text. The interior will be marked up as added text following the
5475 normal rules for what is marked up. A use case for this directive is
5476 when a paragraph has been changed substantially but retains some of
5477 the phrasing of the original paragraph. As latexdiff prefers to find
5478 a minimal difference between two files, such a configuration will
5479 usually lead to a fragmented markup, with several added and deleted
5480 sentences or parts of sentenced and a few remaining phrases marked as
5481 unchanged. With the use of this directive it is possible to mark the
5482 whole modified segment as new, which will then be marked-up `en bloc'
5483 as new, and the old part as one block of deleted material, which is
5484 usually clearer than the fragmented default markup.
5485 C<DIFADD> block directives must be placed into the the body of the new
5486 file. Those directives are ignored in the preamble or in the old file.
5487
5488 =item C<DIFDEL> block
5489
5490 ...
5491 %BEGIN DIFDEL
5492 ...
5493 %END DIFDEL
5494 ...
5495
5496 Everything enclosed between the C<%BEGIN DIFDEL> and C<%END DIFDEL>
5497 directives will be treated as atomistic deleted text.
5498 The interior will be marked up as deleted text following the
5499 normal rules for what is marked up.
5500 C<DIFDEL> block directives must be placed into the the body of the old
5501 file. Those directives are ignored in the preamble or in the new
5502 file.The use case is similar to that of the C<DIFADD> blocks, but the
5503 hint is placed in the old file. In most cases, is sufficient to either
5504 hint in the old file with a C<DIFDEL> block I<or> in the new file with
5505 a C<DIFADD> block and latexdiff will take care of the rest.
5506
5507 =item C<DIFNOMARKUP> block
5508
5509 ...
5510 %BEGIN DIFNOMARKUP
5511 ...
5512 %END DIFNOMARKUP
5513 ...
5514
5515 The text between the markers will be included in the diff algorithm
5516 but no actual markup will be made in this part of the text. It
5517 will show the new text only and suppress the old text. If the text
5518 immediately above the DIFNOMARKUP block has been added a
5519 C<\DIFaddend> will be placed directly above the C<%BEGIN DIFNOMARKUP>
5520 line and any open C<\DIFadd> command terminated, equivalently for
5521 deleted blocks and for text added or deleted immediately after the
5522 C<%BEGIN DIFNOMARKUP>. The main purpose of this command is to salvage
5523 the situation if latexdiff has produced invalid or visually
5524 unacceptable output - markup in the offending passage can be
5525 suppressed by surrounding it with C<DIFNOMARKUP> directives and
5526 rerunning latexdiff, thus enabling markup of the rest of the document (but please
5527 continue to report such failures of latexdiff as described below, so that latexdiff can be improved).
5528 This pair of directives must be placed in the new file and will be
5529 ignored in the old file (or the preambles of either file).
5530
5531
5532
5533 =back
5534
5535 =head1 COMMON PROBLEMS AND FAQ
5536
5537 =over 10
5538
5539 =item Changed citations result in overfull boxes
5540
5541 There is an incompatibility between the C<ulem> package, which C<latexdiff> uses for underlining and striking out in the UNDERLINE style,
5542 the default style, and the way citations are generated. In order to be able to mark up citations properly, they are enclosed with an C<\mbox>
5543 command. As mboxes cannot be broken across lines, this procedure frequently results in overfull boxes, possibly obscuring the content as it extends beyond the right margin. The same occurs for some other packages (e.g., siunitx). If this is a problem, you have several possibilities.
5544
5545 1. Use C<CFONT> type markup (option C<-t CFONT>): If this markup is chosen, then changed citations are no longer marked up
5546 with the wavy line (additions) or struck out (deletions), but are still highlighted in the appropriate color, and deleted text is shown with a different font. Other styles not using the C<ulem> package will also work.
5547
5548 2. Choose option C<--disable-citation-markup> which turns off the marking up of citations: deleted citations are no longer shown, and
5549 added citations are shown without markup. (This was the default behaviour of latexdiff at versions 0.6 and older).
5550 For custom packages you can define the commands which need to be protected by C<\mbox> with C<--append-mboxsafecmd> and C<--excludemboxsafecmd> options
5551 (submit your lists of command as feature request at github page to set the default behaviour of future versions, see section 6)
5552
5553 3. If you are using luatex >= 1.12.0 you can use option LUAUNDERLINE that uses lua-ul instead of ulem for underlining, which does not have this problem (experimental feature).
5554
5555 =item Changes in complicated mathematical equations result in latex processing errors.
5556
5557 Try option C<--math-markup=whole>. If even that fails, you can turn off mark up for equations with C<--math-markup=off>.
5558
5559 =item Deleted parts in equations are not struck out but underlined.
5560
5561 This is a limitation of the ulem package that implements the strike-out. If you use the amsmath package, then the strike-out command is redefined in such a way that deleted passages are wrapped with C<\text> command; adding C<\usepackage{amsmath}> to your preamble will trigger this behaviour. (If amsmath is not included directly, but imported by another package, latexdiff will not be able to detect its availability; in this case you can give latexdiff a hint with option C<--packages=amsmath>.
5562
5563
5564 =item How can I just show the pages where changes had been made?
5565
5566 Use options C<--s ZLABEL> (some postprocessing required) or C<-s ONLYCHANGEDPAGE>. C<latexdiff-vc --ps|--pdf> with C<--only-changes> option takes care of
5567 the post-processing for you (requires zref package to be installed).
5568
5569 =item The character encoding breaks when running latexdiff from powershell.
5570
5571 This problem is not limited to C<latexdiff> and has to do with the default settings of C<powershell> in Windows. It is recommended to use C<cmd> instead.
5572
5573 =back
5574
5575 =head1 KNOWN BUGS
5576
5577 =over 10
5578
5579 =item Option C<--allow-spaces> is not implemented entirely consistently. It breaks
5580 the rules that number and type of white space does not matter, as
5581 different numbers of inter-argument spaces are treated as significant.
5582
5583 =back
5584
5585 Please submit bug reports using the issue tracker of the github repository page I<https://github.com/ftilmann/latexdiff.git>,
5586 or send them to I<tilmann -- AT -- gfz-potsdam.de>. Include the version number of I<latexdiff>
5587 (from comments at the top of the source or use B<--version>). If you come across latex
5588 files that are error-free and conform to the specifications set out
5589 above, and whose differencing still does not result in error-free
5590 latex, please send me those files, ideally edited to only contain the
5591 offending passage as long as that still reproduces the problem. If your
5592 file relies on non-standard class files, you must include those. I will not
5593 look at examples where I have trouble to latex the original files.
5594
5595 =head1 SEE ALSO
5596
5597 L<latexrevise>, L<latexdiff-vc>
5598
5599 =head1 PORTABILITY
5600
5601 I<latexdiff> does not make use of external commands and thus should run
5602 on any platform supporting Perl 5.6 or higher. If files with encodings
5603 other than ASCII or UTF-8 are processed, Perl 5.8 or higher is required.
5604
5605 The standard version of I<latexdiff> requires installation of the Perl package
5606 C<Algorithm::Diff> (available from I<www.cpan.org> -
5607 I<http://search.cpan.org/~nedkonz/Algorithm-Diff-1.15>) but a stand-alone
5608 version, I<latexdiff-so>, which has this package inlined, is available, too.
5609 I<latexdiff-fast> requires the I<diff> command to be present.
5610
5611 =head1 AUTHOR
5612
5613 Version 1.4.0
5614 Copyright (C) 2004-2024 Frederik Tilmann
5615
5616 This program is free software; you can redistribute it and/or modify
5617 it under the terms of the GNU General Public License Version 3
5618
5619 Contributors of fixes and additions: V. Kuhlmann, J. Paisley, N. Becker, T. Doerges, K. Huebner,
5620 T. Connors, Sebastian Gouezel and many others.
5621 Thanks to the many people who sent in bug reports, feature suggestions, and other feedback.
5622
5623 =cut
5624
5625 __END__
5626 %%BEGIN SAFE COMMANDS
5627 % Regex matching commands which can safely be in the
5628 % argument of a \DIFadd or \DIFdel command (leave out the \)
5629 arabic
5630 emph
5631 fbox
5632 hspace\*?
5633 math.*
5634 mbox
5635 pageref
5636 ref
5637 eqref
5638 symbol
5639 rule
5640 text.*
5641 usebox
5642 dag
5643 ddag
5644 copyright
5645 pounds
5646 i
5647 S
5648 P
5649 oe
5650 OE
5651 ae
5652 AE
5653 aa
5654 AA
5655 o
5656 O
5657 l
5658 L
5659 frac
5660 ss
5661 ldots
5662 cdots
5663 vdots
5664 ddots
5665 alpha
5666 beta
5667 gamma
5668 delta
5669 epsilon
5670 varepsilon
5671 zeta
5672 eta
5673 theta
5674 vartheta
5675 iota
5676 kappa
5677 lambda
5678 mu
5679 nu
5680 xi
5681 pi
5682 varpi
5683 rho
5684 varrho
5685 sigma
5686 varsigma
5687 tau
5688 upsilon
5689 phi
5690 varphi
5691 chi
5692 psi
5693 omega
5694 Gamma
5695 Delta
5696 Theta
5697 Lambda
5698 Xi
5699 Pi
5700 Sigma
5701 Upsilon
5702 Phi
5703 Psi
5704 Omega
5705 ps
5706 mp
5707 times
5708 div
5709 ast
5710 star
5711 circ
5712 bullet
5713 cdot
5714 cap
5715 cup
5716 uplus
5717 sqcap
5718 vee
5719 wedge
5720 setminus
5721 wr
5722 diamond
5723 (?:big)?triangle.*
5724 lhd
5725 rhd
5726 unlhd
5727 unrhd
5728 oplus
5729 ominus
5730 otimes
5731 oslash
5732 odot
5733 bigcirc
5734 d?dagger
5735 amalg
5736 leq
5737 prec
5738 preceq
5739 ll
5740 (?:sq)?su[bp]set(?:eq)?
5741 in
5742 vdash
5743 geq
5744 succ(?:eq)?
5745 gg
5746 ni
5747 dashv
5748 equiv
5749 sim(?:eq)?
5750 asymp
5751 approx
5752 cong
5753 neq
5754 doteq
5755 propto
5756 models
5757 perp
5758 mid
5759 parallel
5760 bowtie
5761 Join
5762 smile
5763 frown
5764 .*arrow
5765 (?:long)?mapsto
5766 .*harpoon.*
5767 leadsto
5768 aleph
5769 hbar
5770 imath
5771 jmath
5772 ell
5773 wp
5774 Re
5775 Im
5776 mho
5777 prime
5778 emptyset
5779 nabla
5780 surd
5781 top
5782 bot
5783 angle
5784 forall
5785 exists
5786 neg
5787 flat
5788 natural
5789 sharp
5790 backslash
5791 partial
5792 infty
5793 Box
5794 Diamond
5795 triangle
5796 clubsuit
5797 diamondsuit
5798 heartsuit
5799 spadesuit
5800 sum
5801 prod
5802 coprod
5803 int
5804 oint
5805 big(?:sq)?c[au]p
5806 bigvee
5807 bigwedge
5808 bigodot
5809 bigotimes
5810 bigoplus
5811 biguplus
5812 (?:arc)?(?:cos|sin|tan|cot)h?
5813 csc
5814 arg
5815 deg
5816 det
5817 dim
5818 exp
5819 gcd
5820 hom
5821 inf
5822 ker
5823 lg
5824 lim
5825 liminf
5826 limsup
5827 ln
5828 log
5829 max
5830 min
5831 Pr
5832 sec
5833 sup
5834 quad
5835 qquad
5836 bibfield
5837 bibinfo
5838 [Hclbkdruvt]
5839 [`'^"~=.]
5840 _
5841 AMPERSAND
5842 (SUPER|SUB)SCRIPTNB
5843 (SUPER|SUB)SCRIPT
5844 SQRT
5845 SQRTNB
5846 PERCENTAGE
5847 DOLLAR
5848 %%END SAFE COMMANDS
5849
5850 % Commands with optional or more than one non-optional arguments that are also text commands.
5851 % They were formerly (pre-1.3.5) considered safe, but if a change is made to any of the earlier arguments
5852 % (i.e. not the last one considered text), then invalid code would often result.
5853 % dashbox
5854 % framebox
5855 % makebox
5856 % raisebox
5857 % shortstack
5858 % sqrt
5859
5860
5861
5862 %%BEGIN TEXT COMMANDS
5863 % Regex matching commands with a text argument (leave out the \)
5864 addcontents.*
5865 cc
5866 closing
5867 chapter
5868 dashbox
5869 emph
5870 encl
5871 fbox
5872 framebox
5873 footnote
5874 footnotetext
5875 framebox
5876 href
5877 intertext
5878 part
5879 (sub){0,2}section\*?
5880 (sub)?paragraph\*?
5881 makebox
5882 mbox
5883 opening
5884 parbox
5885 raisebox
5886 savebox
5887 sbox
5888 shortintertext
5889 shortstack
5890 sidenote
5891 signature
5892 text.*
5893 value
5894 underline
5895 sqrt
5896 %%END TEXT COMMANDS
5897
5898 %%BEGIN CONTEXT1 COMMANDS
5899 % Regex matching commands with a text argument (leave out the \), which will fail out of context. These commands behave like text commands, except when they occur in a deleted section, where they are disabled, but their argument is shown as deleted text.
5900 caption
5901 subcaption
5902 multicolumn
5903 %%END CONTEXT1 COMMANDS
5904
5905 %%BEGIN CONTEXT2 COMMANDS
5906 % Regex matching commands with a text argument (leave out the \), which will fail out of context. As corresponding commands for context1. The only difference is that context2 commands are completely disabled in deleted sections, including their arguments.
5907 title
5908 author
5909 date
5910 institute
5911 %%END CONTEXT2 COMMANDS
5912
5913 %% CONFIGURATION variabe defaults
5914 %%BEGIN LISTENV CONFIG
5915 itemize
5916 description
5917 enumerate
5918 %%END LISTENV CONFIG
5919
5920 %%BEGIN FLOATENV CONFIG
5921 figure[\w\d*@]*
5922 table[\w\d*@]*
5923 plate[\w\d*@]*
5924 %%END FLOATENV CONFIG
5925
5926 %%BEGIN PICTUREENV CONFIG
5927 picture[\w\d*@]*
5928 tikzpicture[\w\d*@]*
5929 DIFnomarkup
5930 %%END PICTUREENV CONFIG
5931
5932 %%BEGIN MATHENV CONFIG
5933 equation[*]?
5934 displaymath
5935 math
5936 DOLLARDOLLAR
5937 %%END MATHENV CONFIG
5938
5939 %%BEGIN MATHARRENV CONFIG
5940 eqnarray[*]?
5941 align[*]?
5942 alignat[*]?
5943 gather[*]?
5944 multline[*]?
5945 flalign[*]?
5946 %%END MATHARRENV CONFIG
5947
5948 %%BEGIN ARRENV CONFIG
5949 aligned
5950 gathered
5951 multlined
5952 array
5953 [pbvBV]?matrix
5954 smallmatrix
5955 cases
5956 %%END ARRENV CONFIG
5957 # split
5958
5959
5960 %%BEGIN COUNTERCMD CONFIG
5961 footnote
5962 part
5963 chapter
5964 section
5965 subsection
5966 subsubsection
5967 paragraph
5968 subparagraph
5969 %%END COUNTERCMD CONFIG
5970
5971 %%BEGIN VERBATIMENV CONFIG
5972 comment
5973 %%END VERBATIMENV CONFIG
5974
5975 %%BEGIN VERBATIMLINEENV CONFIG
5976 lstlisting
5977 verbatim[*]?
5978 %%END VERBATIMLINEENV CONFIG
5979
5980 %%BEGIN CUSTOMDIFCMD CONFIG
5981 %%END CUSTOMDIFCMD CONFIG
5982
5983 %%% TYPES (Commands for highlighting changed blocks)
5984
5985 %DIF UNDERLINE PREAMBLE
5986 \RequirePackage[normalem]{ulem}
5987 \RequirePackage{color}\definecolor{RED}{rgb}{1,0,0}\definecolor{BLUE}{rgb}{0,0,1}
5988 \providecommand{\DIFadd}[1]{{\protect\color{blue}\uwave{#1}}}
5989 \providecommand{\DIFdel}[1]{{\protect\color{red}\sout{#1}}}
5990 %DIF END UNDERLINE PREAMBLE
5991
5992 %DIF LUAUNDERLINE PREAMBLE
5993 \RequirePackage{lua-ul}
5994 \RequirePackage{color}\definecolor{RED}{rgb}{1,0,0}\definecolor{BLUE}{rgb}{0,0,1}
5995 \providecommand{\DIFadd}[1]{{\protect\color{blue}\underLine{#1}}}
5996 \providecommand{\DIFdel}[1]{{\protect\color{red}\strikeThrough{#1}}}
5997 %DIF END LUAUNDERLINE PREAMBLE
5998
5999 %DIF CTRADITIONAL PREAMBLE
6000 \RequirePackage{color}\definecolor{RED}{rgb}{1,0,0}\definecolor{BLUE}{rgb}{0,0,1}
6001 \RequirePackage[stable]{footmisc}
6002 \DeclareOldFontCommand{\sf}{\normalfont\sffamily}{\mathsf}
6003 \providecommand{\DIFadd}[1]{{\protect\color{blue} \sf #1}}
6004 \providecommand{\DIFdel}[1]{{\protect\color{red} [..\footnote{removed: #1} ]}}
6005 %DIF END CTRADITIONAL PREAMBLE
6006
6007 %DIF TRADITIONAL PREAMBLE
6008 \RequirePackage[stable]{footmisc}
6009 \DeclareOldFontCommand{\sf}{\normalfont\sffamily}{\mathsf}
6010 \providecommand{\DIFadd}[1]{{\sf #1}}
6011 \providecommand{\DIFdel}[1]{{[..\footnote{removed: #1} ]}}
6012 %DIF END TRADITIONAL PREAMBLE
6013
6014 %DIF CFONT PREAMBLE
6015 \RequirePackage{color}\definecolor{RED}{rgb}{1,0,0}\definecolor{BLUE}{rgb}{0,0,1}
6016 \DeclareOldFontCommand{\sf}{\normalfont\sffamily}{\mathsf}
6017 \providecommand{\DIFadd}[1]{{\protect\color{blue} \sf #1}}
6018 \providecommand{\DIFdel}[1]{{\protect\color{red} \scriptsize #1}}
6019 %DIF END CFONT PREAMBLE
6020
6021 %DIF FONTSTRIKE PREAMBLE
6022 \RequirePackage[normalem]{ulem}
6023 \DeclareOldFontCommand{\sf}{\normalfont\sffamily}{\mathsf}
6024 \providecommand{\DIFadd}[1]{{\sf #1}}
6025 \providecommand{\DIFdel}[1]{{\footnotesize \sout{#1}}}
6026 %DIF END FONTSTRIKE PREAMBLE
6027
6028 %DIF CCHANGEBAR PREAMBLE
6029 \RequirePackage[pdftex]{changebar}
6030 \RequirePackage{color}\definecolor{RED}{rgb}{1,0,0}\definecolor{BLUE}{rgb}{0,0,1}
6031 \providecommand{\DIFadd}[1]{\protect\cbstart{\protect\color{blue}#1}\protect\cbend}
6032 \providecommand{\DIFdel}[1]{\protect\cbdelete{\protect\color{red}#1}\protect\cbdelete}
6033 %DIF END CCHANGEBAR PREAMBLE
6034
6035 %DIF CFONTCHBAR PREAMBLE
6036 \RequirePackage[pdftex]{changebar}
6037 \RequirePackage{color}\definecolor{RED}{rgb}{1,0,0}\definecolor{BLUE}{rgb}{0,0,1}
6038 \providecommand{\DIFadd}[1]{\protect\cbstart{\protect\color{blue}\sf #1}\protect\cbend}
6039 \providecommand{\DIFdel}[1]{\protect\cbdelete{\protect\color{red}\scriptsize #1}\protect\cbdelete}
6040 %DIF END CFONTCHBAR PREAMBLE
6041
6042 %DIF CULINECHBAR PREAMBLE
6043 \RequirePackage[normalem]{ulem}
6044 \RequirePackage[pdftex]{changebar}
6045 \RequirePackage{color}\definecolor{RED}{rgb}{1,0,0}\definecolor{BLUE}{rgb}{0,0,1}
6046 \providecommand{\DIFadd}[1]{\protect\cbstart{\protect\color{blue}\uwave{#1}}\protect\cbend}
6047 \providecommand{\DIFdel}[1]{\protect\cbdelete{\protect\color{red}\sout{#1}}\protect\cbdelete}
6048 %DIF END CULINECHBAR PREAMBLE
6049
6050 %DIF CHANGEBAR PREAMBLE
6051 \RequirePackage[pdftex]{changebar}
6052 \providecommand{\DIFadd}[1]{\protect\cbstart{#1}\protect\cbend}
6053 \providecommand{\DIFdel}[1]{\protect\cbdelete}
6054 %DIF END CHANGEBAR PREAMBLE
6055
6056 %DIF INVISIBLE PREAMBLE
6057 \providecommand{\DIFadd}[1]{#1}
6058 \providecommand{\DIFdel}[1]{}
6059 %DIF END INVISIBLE PREAMBLE
6060
6061 %DIF BOLD PREAMBLE
6062 \DeclareOldFontCommand{\bf}{\normalfont\bfseries}{\mathbf}
6063 \providecommand{\DIFadd}[1]{{\bf #1}}
6064 \providecommand{\DIFdel}[1]{}
6065 %DIF END BOLD PREAMBLE
6066
6067 %DIF PDFCOMMENT PREAMBLE
6068 \RequirePackage{pdfcomment} %DIF PREAMBLE
6069 \providecommand{\DIFadd}[1]{\pdfmarkupcomment[author=ADD:,markup=Underline]{#1}{}}
6070 \providecommand{\DIFdel}[1]{\pdfcomment[icon=Insert,author=DEL:,hspace=12pt]{#1}}
6071 %DIF END PDFCOMMENT PREAMBLE
6072
6073 %% SUBTYPES (Markers for beginning and end of changed blocks)
6074
6075 %DIF SAFE PREAMBLE
6076 \providecommand{\DIFaddbegin}{}
6077 \providecommand{\DIFaddend}{}
6078 \providecommand{\DIFdelbegin}{}
6079 \providecommand{\DIFdelend}{}
6080 \providecommand{\DIFmodbegin}{}
6081 \providecommand{\DIFmodend}{}
6082 %DIF END SAFE PREAMBLE
6083
6084 %DIF MARGIN PREAMBLE
6085 \providecommand{\DIFaddbegin}{\protect\marginpar{a[}}
6086 \providecommand{\DIFaddend}{\protect\marginpar{]}}
6087 \providecommand{\DIFdelbegin}{\protect\marginpar{d[}}
6088 \providecommand{\DIFdelend}{\protect\marginpar{]}}
6089 \providecommand{\DIFmodbegin}{\protect\marginpar{m[}}
6090 \providecommand{\DIFmodend}{\protect\marginpar{]}}
6091 %DIF END MARGIN PREAMBLE
6092
6093 %DIF DVIPSCOL PREAMBLE
6094 %Note: only works with dvips converter
6095 \RequirePackage{color}
6096 \RequirePackage{dvipscol}
6097 \providecommand{\DIFaddbegin}{\protect\nogroupcolor{blue}}
6098 \providecommand{\DIFaddend}{\protect\nogroupcolor{black}}
6099 \providecommand{\DIFdelbegin}{\protect\nogroupcolor{red}}
6100 \providecommand{\DIFdelend}{\protect\nogroupcolor{black}}
6101 \providecommand{\DIFmodbegin}{}
6102 \providecommand{\DIFmodend}{}
6103 %DIF END DVIPSCOL PREAMBLE
6104
6105 %DIF COLOR PREAMBLE
6106 \RequirePackage{color}
6107 \providecommand{\DIFaddbegin}{\protect\color{blue}}
6108 \providecommand{\DIFaddend}{\protect\color{black}}
6109 \providecommand{\DIFdelbegin}{\protect\color{red}}
6110 \providecommand{\DIFdelend}{\protect\color{black}}
6111 \providecommand{\DIFmodbegin}{}
6112 \providecommand{\DIFmodend}{}
6113 %DIF END COLOR PREAMBLE
6114
6115 %DIF LABEL PREAMBLE
6116 % To show only pages with changes (pdf) (external program pdftk needs to be installed)
6117 % (only works for simple documents with non-repeated page numbers, otherwise use ZLABEL)
6118 % pdflatex diff.tex
6119 % pdflatex diff.tex
6120 %pdftk diff.pdf cat \
6121 %`perl -lne '\
6122 % if (m/\\newlabel{DIFchg[b](\d*)}{{.*}{(.*)}}/) { $start{$1}=$2; print $2}\
6123 % if (m/\\newlabel{DIFchg[e](\d*)}{{.*}{(.*)}}/) { \
6124 % if (defined($start{$1})) { \
6125 % for ($j=$start{$1}; $j<=$2; $j++) {print "$j";}\
6126 % } else { \
6127 % print "$2"\
6128 % }\
6129 % }' diff.aux \
6130 % | uniq \
6131 % | tr \\n ' '` \
6132 % output diff-changedpages.pdf
6133 % To show only pages with changes (dvips/dvipdf)
6134 % dvips -pp `\
6135 % [ put here the perl script from above]
6136 % | uniq | tr -s \\n ','`
6137 \typeout{Check comments in preamble of output for instructions how to show only pages where changes have been made}
6138 \newcount\DIFcounterb
6139 \global\DIFcounterb 0\relax
6140 \newcount\DIFcountere
6141 \global\DIFcountere 0\relax
6142 \providecommand{\DIFaddbegin}{\global\advance\DIFcounterb 1\relax\label{DIFchgb\the\DIFcounterb}}
6143 \providecommand{\DIFaddend}{\global\advance\DIFcountere 1\relax\label{DIFchge\the\DIFcountere}}
6144 \providecommand{\DIFdelbegin}{\global\advance\DIFcounterb 1\relax\label{DIFchgb\the\DIFcounterb}}
6145 \providecommand{\DIFdelend}{\global\advance\DIFcountere 1\relax\label{DIFchge\the\DIFcountere}}
6146 \providecommand{\DIFmodbegin}{\global\advance\DIFcounterb 1\relax\label{DIFchgb\the\DIFcounterb}}
6147 \providecommand{\DIFmodend}{\global\advance\DIFcountere 1\relax\label{DIFchge\the\DIFcountere}}
6148 %DIF END LABEL PREAMBLE
6149
6150 %DIF ZLABEL PREAMBLE
6151 % To show only pages with changes (pdf) (external program pdftk needs to be installed)
6152 % (uses zref for reference to absolute page numbers)
6153 % pdflatex diff.tex
6154 % pdflatex diff.tex
6155 %pdftk diff.pdf cat \
6156 %`perl -lne 'if (m/\\zref\@newlabel{DIFchgb(\d*)}{.*\\abspage{(\d*)}}/ ) { $start{$1}=$2; print $2 } \
6157 % if (m/\\zref\@newlabel{DIFchge(\d*)}{.*\\abspage{(\d*)}}/) { \
6158 % if (defined($start{$1})) { \
6159 % for ($j=$start{$1}; $j<=$2; $j++) {print "$j";}\
6160 % } else { \
6161 % print "$2"\
6162 % }\
6163 % }' diff.aux \
6164 % | uniq \
6165 % | tr \\n ' '` \
6166 % output diff-changedpages.pdf
6167 % To show only pages with changes (dvips/dvipdf)
6168 % latex diff.tex
6169 % latex diff.tex
6170 % dvips -pp `perl -lne 'if (m/\\newlabel{DIFchg[be]\d*}{{.*}{(.*)}}/) { print $1 }' diff.aux | uniq | tr -s \\n ','` diff.dvi
6171 \typeout{Check comments in preamble of output for instructions how to show only pages where changes have been made}
6172 \usepackage[user,abspage]{zref}
6173 \newcount\DIFcounterb
6174 \global\DIFcounterb 0\relax
6175 \newcount\DIFcountere
6176 \global\DIFcountere 0\relax
6177 \providecommand{\DIFaddbegin}{\global\advance\DIFcounterb 1\relax\zlabel{DIFchgb\the\DIFcounterb}}
6178 \providecommand{\DIFaddend}{\global\advance\DIFcountere 1\relax\zlabel{DIFchge\the\DIFcountere}}
6179 \providecommand{\DIFdelbegin}{\global\advance\DIFcounterb 1\relax\zlabel{DIFchgb\the\DIFcounterb}}
6180 \providecommand{\DIFdelend}{\global\advance\DIFcountere 1\relax\zlabel{DIFchge\the\DIFcountere}}
6181 \providecommand{\DIFmodbegin}{\global\advance\DIFcounterb 1\relax\zlabel{DIFchgb\the\DIFcounterb}}
6182 \providecommand{\DIFmodend}{\global\advance\DIFcountere 1\relax\zlabel{DIFchge\the\DIFcountere}}
6183 %DIF END ZLABEL PREAMBLE
6184
6185 %DIF ONLYCHANGEDPAGE PREAMBLE
6186 \RequirePackage{atbegshi}
6187 \RequirePackage{etoolbox}
6188 \RequirePackage{zref}
6189 % redefine label command to write immediately to aux file - page references will be lost
6190 \makeatletter \let\oldlabel\label% Store \label
6191 \renewcommand{\label}[1]{% Update \label to write to the .aux immediately
6192 \zref@wrapper@immediate{\oldlabel{#1}}}
6193 \makeatother
6194 \newbool{DIFkeeppage}
6195 \newbool{DIFchange}
6196 \boolfalse{DIFkeeppage}
6197 \boolfalse{DIFchange}
6198 \AtBeginShipout{%
6199 \ifbool{DIFkeeppage}
6200 {\global\boolfalse{DIFkeeppage}} % True DIFkeeppage
6201 {\ifbool{DIFchange}{\global\boolfalse{DIFkeeppage}}{\global\boolfalse{DIFkeeppage}\AtBeginShipoutDiscard}} % False DIFkeeppage
6202 }
6203 \providecommand{\DIFaddbegin}{\global\booltrue{DIFkeeppage}\global\booltrue{DIFchange}}
6204 \providecommand{\DIFaddend}{\global\booltrue{DIFkeeppage}\global\boolfalse{DIFchange}}
6205 \providecommand{\DIFdelbegin}{\global\booltrue{DIFkeeppage}\global\booltrue{DIFchange}}
6206 \providecommand{\DIFdelend}{\global\booltrue{DIFkeeppage}\global\boolfalse{DIFchange}}
6207 \providecommand{\DIFmodbegin}{\global\booltrue{DIFkeeppage}\global\booltrue{DIFchange}}
6208 \providecommand{\DIFmodend}{\global\booltrue{DIFkeeppage}\global\boolfalse{DIFchange}}
6209 %DIF END ONLYCHANGEDPAGE PREAMBLE
6210
6211 %% FLOAT TYPES
6212
6213 %DIF FLOATSAFE PREAMBLE
6214 \providecommand{\DIFaddFL}[1]{\DIFadd{#1}}
6215 \providecommand{\DIFdelFL}[1]{\DIFdel{#1}}
6216 \providecommand{\DIFaddbeginFL}{}
6217 \providecommand{\DIFaddendFL}{}
6218 \providecommand{\DIFdelbeginFL}{}
6219 \providecommand{\DIFdelendFL}{}
6220 %DIF END FLOATSAFE PREAMBLE
6221
6222 %DIF IDENTICAL PREAMBLE
6223 \providecommand{\DIFaddFL}[1]{\DIFadd{#1}}
6224 \providecommand{\DIFdelFL}[1]{\DIFdel{#1}}
6225 \providecommand{\DIFaddbeginFL}{\DIFaddbegin}
6226 \providecommand{\DIFaddendFL}{\DIFaddend}
6227 \providecommand{\DIFdelbeginFL}{\DIFdelbegin}
6228 \providecommand{\DIFdelendFL}{\DIFdelend}
6229 %DIF END IDENTICAL PREAMBLE
6230
6231 %DIF TRADITIONALSAFE PREAMBLE
6232 % procidecommand color to make this work for TRADITIONAL and CTRADITIONAL
6233 \providecommand{\color}[1]{}
6234 \providecommand{\DIFaddFL}[1]{\DIFadd{#1}}
6235 \providecommand{\DIFdel}[1]{{\protect\color{red}[..{\scriptsize {removed: #1}} ]}}
6236 \providecommand{\DIFaddbeginFL}{}
6237 \providecommand{\DIFaddendFL}{}
6238 \providecommand{\DIFdelbeginFL}{}
6239 \providecommand{\DIFdelendFL}{}
6240 %DIF END TRADITIONALSAFE PREAMBLE
6241
6242 % see:
6243 % http://tex.stackexchange.com/questions/47351/can-i-redefine-a-command-to-contain-itself
6244
6245 %DIF HIGHLIGHTGRAPHICS PREAMBLE
6246 \RequirePackage{settobox}
6247 \RequirePackage{letltxmacro}
6248 \newsavebox{\DIFdelgraphicsbox}
6249 \newlength{\DIFdelgraphicswidth}
6250 \newlength{\DIFdelgraphicsheight}
6251 % store original definition of \includegraphics
6252 \LetLtxMacro{\DIFOincludegraphics}{\includegraphics}
6253 \providecommand{\DIFaddincludegraphics}[2][]{{\color{blue}\fbox{\DIFOincludegraphics[#1]{#2}}}}
6254 \providecommand{\DIFdelincludegraphics}[2][]{%
6255 \sbox{\DIFdelgraphicsbox}{\DIFOincludegraphics[#1]{#2}}%
6256 \settoboxwidth{\DIFdelgraphicswidth}{\DIFdelgraphicsbox}
6257 \settoboxtotalheight{\DIFdelgraphicsheight}{\DIFdelgraphicsbox}
6258 \scalebox{\DIFscaledelfig}{%
6259 \parbox[b]{\DIFdelgraphicswidth}{\usebox{\DIFdelgraphicsbox}\\[-\baselineskip] \rule{\DIFdelgraphicswidth}{0em}}\llap{\resizebox{\DIFdelgraphicswidth}{\DIFdelgraphicsheight}{%
6260 \setlength{\unitlength}{\DIFdelgraphicswidth}%
6261 \begin{picture}(1,1)%
6262 \thicklines\linethickness{2pt}
6263 {\color[rgb]{1,0,0}\put(0,0){\framebox(1,1){}}}%
6264 {\color[rgb]{1,0,0}\put(0,0){\line( 1,1){1}}}%
6265 {\color[rgb]{1,0,0}\put(0,1){\line(1,-1){1}}}%
6266 \end{picture}%
6267 }\hspace*{3pt}}}
6268 }
6269 \LetLtxMacro{\DIFOaddbegin}{\DIFaddbegin}
6270 \LetLtxMacro{\DIFOaddend}{\DIFaddend}
6271 \LetLtxMacro{\DIFOdelbegin}{\DIFdelbegin}
6272 \LetLtxMacro{\DIFOdelend}{\DIFdelend}
6273 \DeclareRobustCommand{\DIFaddbegin}{\DIFOaddbegin \let\includegraphics\DIFaddincludegraphics}
6274 \DeclareRobustCommand{\DIFaddend}{\DIFOaddend \let\includegraphics\DIFOincludegraphics}
6275 \DeclareRobustCommand{\DIFdelbegin}{\DIFOdelbegin \let\includegraphics\DIFdelincludegraphics}
6276 \DeclareRobustCommand{\DIFdelend}{\DIFOaddend \let\includegraphics\DIFOincludegraphics}
6277 \LetLtxMacro{\DIFOaddbeginFL}{\DIFaddbeginFL}
6278 \LetLtxMacro{\DIFOaddendFL}{\DIFaddendFL}
6279 \LetLtxMacro{\DIFOdelbeginFL}{\DIFdelbeginFL}
6280 \LetLtxMacro{\DIFOdelendFL}{\DIFdelendFL}
6281 \DeclareRobustCommand{\DIFaddbeginFL}{\DIFOaddbeginFL \let\includegraphics\DIFaddincludegraphics}
6282 \DeclareRobustCommand{\DIFaddendFL}{\DIFOaddendFL \let\includegraphics\DIFOincludegraphics}
6283 \DeclareRobustCommand{\DIFdelbeginFL}{\DIFOdelbeginFL \let\includegraphics\DIFdelincludegraphics}
6284 \DeclareRobustCommand{\DIFdelendFL}{\DIFOaddendFL \let\includegraphics\DIFOincludegraphics}
6285 %DIF END HIGHLIGHTGRAPHICS PREAMBLE
6286
6287 %% SPECIAL PACKAGE PREAMBLE COMMANDS
6288
6289 %% Redefine strike out command to wrap in text box if amsmath is used and markup style with ulem is used
6290 %DIF AMSMATHULEM PREAMBLE
6291 \makeatletter
6292 \let\sout@orig\sout
6293 \renewcommand{\sout}[1]{\ifmmode\text{\sout@orig{\ensuremath{#1}}}\else\sout@orig{#1}\fi}
6294 \makeatother
6295 %DIF END AMSMATHULEM PREAMBLE
6296
6297
6298 % Standard \DIFadd and \DIFdel are redefined as \DIFaddtex and \DIFdeltex
6299 % when hyperref package is included.
6300 %DIF HYPERREF PREAMBLE
6301 \providecommand{\DIFadd}[1]{\texorpdfstring{\DIFaddtex{#1}}{#1}}
6302 \providecommand{\DIFdel}[1]{\texorpdfstring{\DIFdeltex{#1}}{}}
6303 %DIF END HYPERREF PREAMBLE
6304
6305 %DIF LISTINGS PREAMBLE
6306 \RequirePackage{listings}
6307 \lstdefinelanguage{DIFcode}{
6308 % note that the definitions in the following two lines are overwritten dependent on the markup type selected %DIFCODE TEMPLATE
6309 morecomment=[il]{\%DIF\ <\ }, %DIFCODE TEMPLATE
6310 moredelim=[il][\bfseries]{\%DIF\ >\ } %DIFCODE TEMPLATE
6311 }
6312 \lstdefinestyle{DIFverbatimstyle}{
6313 language=DIFcode,
6314 basicstyle=\ttfamily,
6315 columns=fullflexible,
6316 keepspaces=true
6317 }
6318 \lstnewenvironment{DIFverbatim}[1][]{\lstset{style=DIFverbatimstyle,#1}}{}
6319 \lstnewenvironment{DIFverbatim*}[1][]{\lstset{style=DIFverbatimstyle,showspaces=true,#1}}{}
6320 %DIF END LISTINGS PREAMBLE
6321
6322 %DIF COLORLISTINGS PREAMBLE
6323 \RequirePackage{listings}
6324 \RequirePackage{color}
6325 \lstdefinelanguage{DIFcode}{
6326 % note that the definitions in the following two lines are overwritten dependent on the markup type selected %DIFCODE TEMPLATE
6327 morecomment=[il]{\%DIF\ <\ }, %DIFCODE TEMPLATE
6328 moredelim=[il][\bfseries]{\%DIF\ >\ } %DIFCODE TEMPLATE
6329 }
6330 \lstdefinestyle{DIFverbatimstyle}{
6331 language=DIFcode,
6332 basicstyle=\ttfamily,
6333 columns=fullflexible,
6334 keepspaces=true
6335 }
6336 \lstnewenvironment{DIFverbatim}[1][]{\lstset{style=DIFverbatimstyle}}{}
6337 \lstnewenvironment{DIFverbatim*}[1][]{\lstset{style=DIFverbatimstyle,showspaces=true}}{}
6338 %DIF END COLORLISTINGS PREAMBLE
6339
6340 %DIF DIFCODE_UNDERLINE
6341 moredelim=[il][\color{red}\sout]{\%DIF\ <\ },
6342 moredelim=[il][\color{blue}\uwave]{\%DIF\ >\ }
6343 %DIF END DIFCODE_UNDERLINE
6344
6345 %DIF DIFCODE_CTRADITIONAL
6346 moredelim=[il][\color{red}\scriptsize]{\%DIF\ <\ },
6347 moredelim=[il][\color{blue}\sffamily]{\%DIF\ >\ }
6348 %DIF END DIFCODE_CTRADITIONAL
6349
6350 %DIF DIFCODE_TRADITIONAL
6351 moredelim=[il][\color{white}\tiny]{\%DIF\ <\ },
6352 moredelim=[il][\sffamily]{\%DIF\ >\ }
6353 %DIF END DIFCODE_TRADITIONAL
6354
6355 %DIF DIFCODE_CFONT
6356 moredelim=[il][\color{red}\scriptsize]{\%DIF\ <\ },
6357 moredelim=[il][\color{blue}\sffamily]{\%DIF\ >\ }
6358 %DIF END DIFCODE_CFONT
6359
6360 %DIF DIFCODE_FONTSTRIKE
6361 moredelim=[il][\scriptsize \sout]{\%DIF\ <\ },
6362 moredelim=[il][\sffamily]{\%DIF\ >\ }
6363 %DIF END DIFCODE_FONTSTRIKE
6364
6365 %DIF DIFCODE_INVISIBLE
6366 moredelim=[il][\color{white}\tiny]{\%DIF\ <\ },
6367 moredelim=[il]{\%DIF\ >\ }
6368 %DIF END DIFCODE_INVISIBLE
6369
6370 %DIF DIFCODE_CHANGEBAR
6371 moredelim=[il][\color{white}\tiny]{\%DIF\ <\ },
6372 moredelim=[il]{\%DIF\ >\ }
6373 %DIF END DIFCODE_CHANGEBAR
6374
6375 %DIF DIFCODE_CCHANGEBAR
6376 moredelim=[il][\color{red}]{\%DIF\ <\ },
6377 moredelim=[il][\color{blue}]{\%DIF\ >\ }
6378 %DIF END DIFCODE_CCHANGEBAR
6379
6380 %DIF DIFCODE_CULINECHBAR
6381 moredelim=[il][\color{red}\sout]{\%DIF\ <\ },
6382 moredelim=[il][\color{blue}\uwave]{\%DIF\ >\ }
6383 %DIF END DIFCODE_CULINECHBAR
6384
6385 %DIF DIFCODE_CFONTCHBAR
6386 moredelim=[il][\color{red}\scriptsize]{\%DIF\ <\ },
6387 moredelim=[il][\color{blue}\sffamily]{\%DIF\ >\ }
6388 %DIF END DIFCODE_CFONTCHBAR
6389
6390 %DIF DIFCODE_BOLD
6391 % unfortunately \bfseries cannot be combined with ttfamily without extra packages
6392 % also morecomment=[il] is broken as of v1.5b of listings at least
6393 % workaround: plot in white with tiny font
6394 % morecomment=[il]{\%DIF\ <\ },
6395 moredelim=[il][\color{white}\tiny]{\%DIF\ <\ },
6396 moredelim=[il][\sffamily\bfseries]{\%DIF\ >\ }
6397 %DIF END DIFCODE_BOLD
6398
6399 %DIF DIFCODE_PDFCOMMENT
6400
6401 moredelim=[il][\color{white}\tiny]{\%DIF\ <\ },
6402 moredelim=[il][\sffamily\bfseries]{\%DIF\ >\ }
6403 %DIF END DIFCODE_PDFCOMMENT
6404