]> git.lyx.org Git - lyx.git/blob - src/Compare.cpp
Fix #10778 (issue with CJK and language nesting)
[lyx.git] / src / Compare.cpp
1 /**
2  * \file Compare.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Vincent van Ravesteijn
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Compare.h"
14
15 #include "Author.h"
16 #include "BufferParams.h"
17 #include "Changes.h"
18 #include "CutAndPaste.h"
19 #include "ErrorList.h"
20 #include "Font.h"
21
22 #include "insets/InsetText.h"
23
24 #include "support/lassert.h"
25 #include "support/lyxalgo.h"
26 #include "support/qstring_helpers.h"
27
28 using namespace std;
29 using namespace lyx::support;
30
31
32 namespace lyx {
33
34
35 enum Direction {
36         Forward = 0,
37         Backward
38 };
39
40
41 static void step(DocIterator & dit, Direction direction)
42 {
43         if (direction == Forward)
44                 dit.top().forwardPos();
45         else
46                 dit.top().backwardPos();
47 }
48
49
50 static void step(DocIterator & dit, DocIterator const & end, Direction direction)
51 {
52         if (dit != end)
53                 step(dit, direction);
54 }
55
56
57 /**
58  * A pair of two DocIterators that form a range.
59  */
60 class DocRange {
61 public:
62         DocRange(DocIterator const & from_, DocIterator const & to_)
63                 : from(from_), to(to_)
64         {}
65
66         DocRange(Buffer const * buf)
67         {
68                 from = doc_iterator_begin(buf);
69                 to = doc_iterator_end(buf);
70                 to.backwardPos();
71         }
72
73         ///
74         Text * text() const { return from.text(); }
75         ///
76         bool empty() const { return to <= from; }
77         ///
78         size_t length() const;
79
80         /// The begin of the range
81         DocIterator from;
82         /// The end of the range
83         DocIterator to;
84 };
85
86
87 size_t DocRange::length() const
88 {
89         ParagraphList const & ps = from.text()->paragraphs();
90         size_t length = 0;
91         pit_type pit = from.pit();
92         pit_type const endpit = to.pit();
93         for (; pit < endpit; ++pit)
94                 length += ps[pit].size() + 1;
95         length += to.pos() - from.pos();
96         return length;
97 }
98
99
100 class DocPair {
101 public:
102         DocPair()
103         {}
104
105         DocPair(DocIterator o_, DocIterator n_)
106                 : o(o_), n(n_)
107         {}
108
109         bool operator!=(DocPair const & rhs)
110         {
111                 // this might not be intuitive but correct for our purpose
112                 return o != rhs.o && n != rhs.n;
113         }
114
115
116         DocPair & operator++()
117         {
118                 step(o, Forward);
119                 step(n, Forward);
120                 return *this;
121         }
122
123         DocPair & operator--()
124         {
125                 step(o, Backward);
126                 step(n, Backward);
127                 return *this;
128         }
129         ///
130         DocIterator o;
131         ///
132         DocIterator n;
133 };
134
135 /**
136  * A pair of two DocRanges.
137  */
138 class DocRangePair {
139 public:
140         DocRangePair(DocRange const & o_, DocRange const & n_)
141                 : o(o_), n(n_)
142         {}
143
144         DocRangePair(DocPair const & from, DocPair const & to)
145                 : o(from.o, to.o), n(from.n, to.n)
146         {}
147
148         DocRangePair(Buffer const * o_buf, Buffer const * n_buf)
149                 : o(o_buf), n(n_buf)
150         {}
151
152         /// Returns the from pair
153         DocPair from() const
154         {
155                 return DocPair(o.from, n.from);
156         }
157
158         /// Returns the to pair
159         DocPair to() const
160         {
161                 return DocPair(o.to, n.to);
162         }
163
164         DocRange o;
165         DocRange n;
166 };
167
168
169 static DocRangePair stepIntoInset(DocPair const & inset_location)
170 {
171         DocRangePair rp(inset_location, inset_location);
172         rp.o.from.forwardPos();
173         rp.n.from.forwardPos();
174         step(rp.o.to, Forward);
175         step(rp.n.to, Forward);
176         rp.o.to.backwardPos();
177         rp.n.to.backwardPos();
178         return rp;
179 }
180
181
182 /**
183  *  This class is designed to hold a vector that has both positive as
184  *  negative indices. It is internally represented as two vectors, one
185  *  for non-zero indices and one for negative indices. In this way, the
186  *  vector can grow in both directions.
187  *    If an index is not available in the vector, the default value is
188  *  returned. If an object is put in the vector beyond its size, the
189  *  empty spots in between are also filled with the default value.
190  */
191 template<class T>
192 class compl_vector {
193 public:
194         compl_vector()
195         {}
196
197         void reset(T const & def)
198         {
199                 default_ = def;
200                 Vp_.clear();
201                 Vn_.clear();
202         }
203
204         /// Gets the value at index. If it is not in the vector
205         /// the default value is inserted and returned.
206         T & operator[](int index) {
207                 vector<T> & V = index >= 0 ? Vp_ : Vn_;
208                 unsigned int const ii = index >= 0 ? index : -index - 1;
209                 while (ii >= V.size())
210                         V.push_back(default_);
211                 return V[ii];
212         }
213
214 private:
215         /// The vector for positive indices
216         vector<T> Vp_;
217         /// The vector for negative indices
218         vector<T> Vn_;
219         /// The default value that is inserted in the vector
220         /// if more space is needed
221         T default_;
222 };
223
224
225 /**
226  * The implementation of the algorithm that does the comparison
227  * between two documents.
228  */
229 class Compare::Impl {
230 public:
231         ///
232         Impl(Compare const & compare)
233                 : abort_(false), n_(0), m_(0), offset_reverse_diagonal_(0),
234                   odd_offset_(0), compare_(compare),
235                   old_buf_(0), new_buf_(0), dest_buf_(0), dest_pars_(0),
236                   recursion_level_(0), nested_inset_level_(0), D_(0)
237         {}
238
239         ///
240         ~Impl()
241         {}
242
243         // Algorithm to find the shortest edit string. This algorithm
244         // only needs a linear amount of memory (linear with the sum
245         // of the number of characters in the two paragraph-lists).
246         bool diff(Buffer const * new_buf, Buffer const * old_buf,
247                 Buffer const * dest_buf);
248
249         /// Set to true to cancel the algorithm
250         bool abort_;
251
252         ///
253         QString status()
254         {
255                 QString status;
256                 status += toqstr("recursion level:") + " " + QString::number(recursion_level_)
257                         + " " + toqstr("differences:") + " " + QString::number(D_);
258                 return status;
259         }
260
261 private:
262         /// Finds the middle snake and returns the length of the
263         /// shortest edit script.
264         int findMiddleSnake(DocRangePair const & rp, DocPair & middle_snake);
265
266         enum SnakeResult {
267                 NoSnake,
268                 SingleSnake,
269                 NormalSnake
270         };
271
272         /// Retrieve the middle snake when there is overlap between
273         /// the forward and backward path.
274         SnakeResult retrieveMiddleSnake(int k, int D, Direction direction,
275                 DocPair & middle_snake);
276
277         /// Find the furthest reaching D-path (number of horizontal
278         /// and vertical steps; differences between the old and new
279         /// document) in the k-diagonal (vertical minus horizontal steps).
280         void furthestDpathKdiagonal(int D, int k,
281                 DocRangePair const & rp, Direction direction);
282
283         /// Is there overlap between the forward and backward path
284         bool overlap(int k, int D);
285
286         /// This function is called recursively by a divide and conquer
287         /// algorithm. Each time, the string is divided into two split
288         /// around the middle snake.
289         void diff_i(DocRangePair const & rp);
290
291         /// Processes the split chunks. It either adds them as deleted,
292         /// as added, or call diff_i for further processing.
293         void diffPart(DocRangePair const & rp);
294
295         /// Runs the algorithm for the inset located at /c it and /c it_n
296         /// and adds the result to /c pars.
297         void diffInset(Inset * inset, DocPair const & p);
298
299         /// Adds the snake to the destination buffer. The algorithm will
300         /// recursively be applied to any InsetTexts that are within the snake.
301         void processSnake(DocRangePair const & rp);
302
303         /// Writes the range to the destination buffer
304         void writeToDestBuffer(DocRange const & range,
305                 Change::Type type = Change::UNCHANGED);
306
307         /// Writes the paragraph list to the destination buffer
308         void writeToDestBuffer(ParagraphList const & copy_pars) const;
309
310         /// The length of the old chunk currently processed
311         int n_;
312         /// The length of the new chunk currently processed
313         int m_;
314         /// The offset diagonal of the reverse path of the
315         /// currently processed chunk
316         int offset_reverse_diagonal_;
317         /// Is the offset odd or even ?
318         bool odd_offset_;
319
320         /// The thread object, used to emit signals to the GUI
321         Compare const & compare_;
322
323         /// The buffer containing text that will be marked as old
324         Buffer const * old_buf_;
325         /// The buffer containing text that will be marked as new
326         Buffer const * new_buf_;
327         /// The buffer containing text that will be marked as new
328         Buffer const * dest_buf_;
329
330         /// The paragraph list of the destination buffer
331         ParagraphList * dest_pars_;
332
333         /// The level of recursion
334         int recursion_level_;
335
336         /// The number of nested insets at this level
337         int nested_inset_level_;
338
339         /// The position/snake in the old/new document
340         /// of the forward/reverse search
341         compl_vector<DocIterator> ofp;
342         compl_vector<DocIterator> nfp;
343         compl_vector<DocIterator> ofs;
344         compl_vector<DocIterator> nfs;
345         compl_vector<DocIterator> orp;
346         compl_vector<DocIterator> nrp;
347         compl_vector<DocIterator> ors;
348         compl_vector<DocIterator> nrs;
349
350         /// The number of differences in the path the algorithm
351         /// is currently processing.
352         int D_;
353 };
354
355 /////////////////////////////////////////////////////////////////////
356 //
357 // Compare
358 //
359 /////////////////////////////////////////////////////////////////////
360
361 Compare::Compare(Buffer const * new_buf, Buffer const * old_buf,
362         Buffer * const dest_buf, CompareOptions const & options)
363         : new_buffer(new_buf), old_buffer(old_buf), dest_buffer(dest_buf),
364           options_(options), pimpl_(new Impl(*this))
365 {
366         connect(&status_timer_, SIGNAL(timeout()),
367                 this, SLOT(doStatusMessage()));
368         status_timer_.start(1000);
369 }
370
371
372 void Compare::doStatusMessage()
373 {
374         statusMessage(pimpl_->status());
375 }
376
377
378 void Compare::run()
379 {
380         if (!dest_buffer || !new_buffer || !old_buffer)
381                 return;
382
383         // Copy the buffer params to the destination buffer
384         dest_buffer->params() = options_.settings_from_new
385                 ? new_buffer->params() : old_buffer->params();
386         // Copy extra authors to the destination buffer
387         AuthorList const & extra_authors = options_.settings_from_new ?
388                 old_buffer->params().authors() : new_buffer->params().authors();
389         AuthorList::Authors::const_iterator it = extra_authors.begin();
390         for (; it != extra_authors.end(); ++it)
391                 dest_buffer->params().authors().record(*it);
392
393         // We will need this later
394         DocumentClassConstPtr const olddc = 
395                 dest_buffer->params().documentClassPtr();
396         // We do not want to share the DocumentClass with the other Buffer.
397         // See bug #10295.
398         dest_buffer->params().makeDocumentClass();
399
400         doStatusMessage();
401         // Do the real work
402         if (!doCompare())
403                 return;
404
405         // The comparison routine simply copies the paragraphs over into the
406         // new buffer with the document class from wherever they came from.
407         // So we need to reset the document class of all the paragraphs.
408         // See bug #10295.
409         ErrorList el;
410         cap::switchBetweenClasses(
411                         olddc, dest_buffer->params().documentClassPtr(),
412                         static_cast<InsetText &>(dest_buffer->inset()), el);
413
414         finished(pimpl_->abort_);
415         return;
416 }
417
418
419 int Compare::doCompare()
420 {
421         return pimpl_->diff(new_buffer, old_buffer, dest_buffer);
422 }
423
424
425 void Compare::abort()
426 {
427         pimpl_->abort_ = true;
428         condition_.wakeOne();
429         wait();
430         pimpl_->abort_ = false;
431 }
432
433
434 static void getParagraphList(DocRange const & range,
435         ParagraphList & pars)
436 {
437         // Clone the paragraphs within the selection.
438         pit_type startpit = range.from.pit();
439         pit_type endpit = range.to.pit();
440         ParagraphList const & ps_ = range.text()->paragraphs();
441         ParagraphList tmp_pars(lyx::next(ps_.begin(), startpit),
442                 lyx::next(ps_.begin(), endpit + 1));
443
444         // Remove the end of the last paragraph; afterwards, remove the
445         // beginning of the first paragraph. Keep this order - there may only
446         // be one paragraph!
447         Paragraph & back = tmp_pars.back();
448         back.eraseChars(range.to.pos(), back.size(), false);
449         Paragraph & front = tmp_pars.front();
450         front.eraseChars(0, range.from.pos(), false);
451
452         pars.insert(pars.begin(), tmp_pars.begin(), tmp_pars.end());
453 }
454
455
456 static bool equal(Inset const * i_o, Inset const * i_n)
457 {
458         if (!i_o || !i_n)
459                 return false;
460
461         // Different types of insets
462         if (i_o->lyxCode() != i_n->lyxCode())
463                 return false;
464
465         // Editable insets are assumed to be the same as they are of the
466         // same type. If we later on decide that we insert them in the
467         // document as being unchanged, we will run the algorithm on the
468         // contents of the two insets.
469         // FIXME: This fails if the parameters of the insets differ.
470         // FIXME: We do not recurse into InsetTabulars.
471         // FIXME: We need methods inset->equivalent(inset).
472         if (i_o->editable() && !i_o->asInsetMath()
473                   && i_o->asInsetText())
474                 return true;
475
476         ostringstream o_os;
477         ostringstream n_os;
478         i_o->write(o_os);
479         i_n->write(n_os);
480         return o_os.str() == n_os.str();
481 }
482
483
484 static bool equal(DocIterator & o, DocIterator & n)
485 {
486         // Explicitly check for this, so we won't call
487         // Paragraph::getChar for the last pos.
488         bool const o_lastpos = o.pos() == o.lastpos();
489         bool const n_lastpos = n.pos() == n.lastpos();
490         if (o_lastpos || n_lastpos)
491                 return o_lastpos && n_lastpos;
492
493         Paragraph const & old_par = o.text()->getPar(o.pit());
494         Paragraph const & new_par = n.text()->getPar(n.pit());
495
496         char_type const c_o = old_par.getChar(o.pos());
497         char_type const c_n = new_par.getChar(n.pos());
498         if (c_o != c_n)
499                 return false;
500
501         if (old_par.isInset(o.pos())) {
502                 Inset const * i_o = old_par.getInset(o.pos());
503                 Inset const * i_n = new_par.getInset(n.pos());
504
505                 if (i_o && i_n)
506                         return equal(i_o, i_n);
507         }
508
509         Font fo = old_par.getFontSettings(o.buffer()->params(), o.pos());
510         Font fn = new_par.getFontSettings(n.buffer()->params(), n.pos());
511         return fo == fn;
512 }
513
514
515 /// Traverses a snake in a certain direction. p points to a
516 /// position in the old and new file and they are synchronously
517 /// moved along the snake. The function returns true if a snake
518 /// was found.
519 static bool traverseSnake(DocPair & p, DocRangePair const & range,
520         Direction direction)
521 {
522         bool ret = false;
523         DocPair const & p_end =
524                 direction == Forward ? range.to() : range.from();
525
526         while (p != p_end) {
527                 if (direction == Backward)
528                         --p;
529                 if (!equal(p.o, p.n)) {
530                         if (direction == Backward)
531                                 ++p;
532                         return ret;
533                 }
534                 if (direction == Forward)
535                         ++p;
536                 ret = true;
537         }
538         return ret;
539 }
540
541
542 /////////////////////////////////////////////////////////////////////
543 //
544 // Compare::Impl
545 //
546 /////////////////////////////////////////////////////////////////////
547
548
549 void Compare::Impl::furthestDpathKdiagonal(int D, int k,
550          DocRangePair const & rp, Direction direction)
551 {
552         compl_vector<DocIterator> & op = direction == Forward ? ofp : orp;
553         compl_vector<DocIterator> & np = direction == Forward ? nfp : nrp;
554         compl_vector<DocIterator> & os = direction == Forward ? ofs : ors;
555         compl_vector<DocIterator> & ns = direction == Forward ? nfs : nrs;
556
557         // A vertical step means stepping one character in the new document.
558         bool vertical_step = k == -D;
559         if (!vertical_step && k != D) {
560                 vertical_step = direction == Forward
561                         ? op[k - 1] < op[k + 1] : op[k - 1] > op[k + 1];
562         }
563
564         // Where do we take the step from ?
565         int const kk = vertical_step ? k + 1 : k - 1;
566         DocPair p(op[kk], np[kk]);
567         DocPair const s(os[kk], ns[kk]);
568
569         // If D==0 we simulate a vertical step from (0,-1) by doing nothing.
570         if (D != 0) {
571                 // Take a step
572                 if (vertical_step && direction == Forward)
573                         step(p.n, rp.n.to, direction);
574                 else if (vertical_step && direction == Backward)
575                         step(p.n, rp.n.from, direction);
576                 else if (!vertical_step && direction == Forward)
577                         step(p.o, rp.o.to, direction);
578                 else if (!vertical_step && direction == Backward)
579                         step(p.o, rp.o.from, direction);
580         }
581
582         // Traverse snake
583         if (traverseSnake(p, rp, direction)) {
584                 // Record last snake
585                 os[k] = p.o;
586                 ns[k] = p.n;
587         } else {
588                 // Copy last snake from the previous step
589                 os[k] = s.o;
590                 ns[k] = s.n;
591         }
592
593         //Record new position
594         op[k] = p.o;
595         np[k] = p.n;
596 }
597
598
599 bool Compare::Impl::overlap(int k, int D)
600 {
601         // To generalize for the forward and reverse checks
602         int kk = offset_reverse_diagonal_ - k;
603
604         // Can we have overlap ?
605         if (kk <= D && kk >= -D) {
606                 // Do we have overlap ?
607                 if (odd_offset_)
608                         return ofp[k] >= orp[kk] && nfp[k] >= nrp[kk];
609                 else
610                         return ofp[kk] >= orp[k] && nfp[kk] >= nrp[k];
611         }
612         return false;
613 }
614
615
616 Compare::Impl::SnakeResult Compare::Impl::retrieveMiddleSnake(
617         int k, int D, Direction direction, DocPair & middle_snake)
618 {
619         compl_vector<DocIterator> & os = direction == Forward ? ofs : ors;
620         compl_vector<DocIterator> & ns = direction == Forward ? nfs : nrs;
621         compl_vector<DocIterator> & os_r = direction == Forward ? ors : ofs;
622         compl_vector<DocIterator> & ns_r = direction == Forward ? nrs : nfs;
623
624         // The diagonal while doing the backward search
625         int kk = -k + offset_reverse_diagonal_;
626
627         // Did we find a snake ?
628         if (os[k].empty() && os_r[kk].empty()) {
629                 // No, there is no snake at all, in which case
630                 // the length of the shortest edit script is M+N.
631                 LATTEST(2 * D - odd_offset_ == m_ + n_);
632                 return NoSnake;
633         }
634
635         if (os[k].empty()) {
636                 // Yes, but there is only 1 snake and we found it in the
637                 // reverse path.
638                 middle_snake.o = os_r[kk];
639                 middle_snake.n = ns_r[kk];
640                 return SingleSnake;
641         }
642
643         middle_snake.o = os[k];
644         middle_snake.n = ns[k];
645         return NormalSnake;
646 }
647
648
649 int Compare::Impl::findMiddleSnake(DocRangePair const & rp,
650         DocPair & middle_snake)
651 {
652         // The lengths of the old and new chunks.
653         n_ = rp.o.length();
654         m_ = rp.n.length();
655
656         // Forward paths are centered around the 0-diagonal; reverse paths
657         // are centered around the diagonal N - M. (Delta in the article)
658         offset_reverse_diagonal_ = n_ - m_;
659
660         // If the offset is odd, only check for overlap while extending forward
661     // paths, otherwise only check while extending reverse paths.
662         odd_offset_ = (offset_reverse_diagonal_ % 2 != 0);
663
664         ofp.reset(rp.o.from);
665         nfp.reset(rp.n.from);
666         ofs.reset(DocIterator());
667         nfs.reset(DocIterator());
668         orp.reset(rp.o.to);
669         nrp.reset(rp.n.to);
670         ors.reset(DocIterator());
671         nrs.reset(DocIterator());
672
673         // In the formula below, the "+ 1" ensures we round like ceil()
674         int const D_max = (m_ + n_ + 1)/2;
675         // D is the number of horizontal and vertical steps, i.e.
676         // different characters in the old and new chunk.
677         for (int D = 0; D <= D_max; ++D) {
678                 // to be used in the status messages
679                 D_ = D;
680
681                 // Forward and reverse paths
682                 for (int f = 0; f < 2; ++f) {
683                         Direction direction = f == 0 ? Forward : Backward;
684
685                         // Diagonals between -D and D can be reached by a D-path
686                         for (int k = -D; k <= D; k += 2) {
687                                 // Find the furthest reaching D-path on this diagonal
688                                 furthestDpathKdiagonal(D, k, rp, direction);
689
690                                 // Only check for overlap for forward paths if the offset is odd
691                                 // and only for reverse paths if the offset is even.
692                                 if (odd_offset_ == (direction == Forward)) {
693
694                                         // Do the forward and backward paths overlap ?
695                                         if (overlap(k, D - odd_offset_)) {
696                                                 retrieveMiddleSnake(k, D, direction, middle_snake);
697                                                 return 2 * D - odd_offset_;
698                                         }
699                                 }
700                                 if (abort_)
701                                         return 0;
702                         }
703                 }
704         }
705         // This should never be reached
706         return -2;
707 }
708
709
710 bool Compare::Impl::diff(Buffer const * new_buf, Buffer const * old_buf,
711         Buffer const * dest_buf)
712 {
713         if (!new_buf || !old_buf || !dest_buf)
714                 return false;
715
716         old_buf_ = old_buf;
717         new_buf_ = new_buf;
718         dest_buf_ = dest_buf;
719         dest_pars_ = &dest_buf->inset().asInsetText()->paragraphs();
720         dest_pars_->clear();
721
722         recursion_level_ = 0;
723         nested_inset_level_ = 0;
724
725         DocRangePair rp(old_buf_, new_buf_);
726
727         DocPair from = rp.from();
728         traverseSnake(from, rp, Forward);
729         DocRangePair const snake(rp.from(), from);
730         processSnake(snake);
731
732         // Start the recursive algorithm
733         DocRangePair rp_new(from, rp.to());
734         if (!rp_new.o.empty() || !rp_new.n.empty())
735                 diff_i(rp_new);
736
737         for (pit_type p = 0; p < (pit_type)dest_pars_->size(); ++p) {
738                 (*dest_pars_)[p].setBuffer(const_cast<Buffer &>(*dest_buf));
739                 (*dest_pars_)[p].setInsetOwner(&dest_buf_->inset());
740         }
741
742         return true;
743 }
744
745
746 void Compare::Impl::diff_i(DocRangePair const & rp)
747 {
748         if (abort_)
749                 return;
750
751         // The middle snake
752         DocPair middle_snake;
753
754         // Divides the problem into two smaller problems, split around
755         // the snake in the middle.
756         int const L_ses = findMiddleSnake(rp, middle_snake);
757
758         // Set maximum of progress bar
759         if (++recursion_level_ == 1)
760                 compare_.progressMax(L_ses);
761
762         // There are now three possibilities: the strings were the same,
763         // the strings were completely different, or we found a middle
764         // snake and we can split the string into two parts to process.
765         if (L_ses == 0)
766                 // Two the same strings (this must be a very rare case, because
767                 // usually this will be part of a snake adjacent to these strings).
768                 writeToDestBuffer(rp.o);
769
770         else if (middle_snake.o.empty()) {
771                 // Two totally different strings
772                 writeToDestBuffer(rp.o, Change::DELETED);
773                 writeToDestBuffer(rp.n, Change::INSERTED);
774
775         } else {
776                 // Retrieve the complete snake
777                 DocPair first_part_end = middle_snake;
778                 traverseSnake(first_part_end, rp, Backward);
779                 DocRangePair first_part(rp.from(), first_part_end);
780
781                 DocPair second_part_begin = middle_snake;
782                 traverseSnake(second_part_begin, rp, Forward);
783                 DocRangePair second_part(second_part_begin, rp.to());
784
785                 // Split the string in three parts:
786                 // 1. in front of the snake
787                 diffPart(first_part);
788
789                 // 2. the snake itself, and
790                 DocRangePair const snake(first_part.to(), second_part.from());
791                 processSnake(snake);
792
793                 // 3. behind the snake.
794                 diffPart(second_part);
795         }
796         --recursion_level_;
797 }
798
799
800 void Compare::Impl::diffPart(DocRangePair const & rp)
801 {
802         // Is there a finite length string in both buffers, if not there
803         // is an empty string and we write the other one to the buffer.
804         if (!rp.o.empty() && !rp.n.empty())
805                 diff_i(rp);
806
807         else if (!rp.o.empty())
808                 writeToDestBuffer(rp.o, Change::DELETED);
809
810         else if (!rp.n.empty())
811                 writeToDestBuffer(rp.n, Change::INSERTED);
812 }
813
814
815 void Compare::Impl::diffInset(Inset * inset, DocPair const & p)
816 {
817         // Find the dociterators for the beginning and the
818         // end of the inset, for the old and new document.
819         DocRangePair const rp = stepIntoInset(p);
820
821         // Recurse into the inset. Temporarily replace the dest_pars
822         // paragraph list by the paragraph list of the nested inset.
823         ParagraphList * backup_dest_pars = dest_pars_;
824         dest_pars_ = &inset->asInsetText()->text().paragraphs();
825         dest_pars_->clear();
826
827         ++nested_inset_level_;
828         diff_i(rp);
829         --nested_inset_level_;
830
831         dest_pars_ = backup_dest_pars;
832 }
833
834
835 void Compare::Impl::processSnake(DocRangePair const & rp)
836 {
837         ParagraphList pars;
838         getParagraphList(rp.o, pars);
839
840         // Find insets in this paragaph list
841         DocPair it = rp.from();
842         for (; it.o < rp.o.to; ++it) {
843                 Inset * inset = it.o.text()->getPar(it.o.pit()).getInset(it.o.pos());
844                 if (inset && inset->editable() && inset->asInsetText()) {
845                         // Find the inset in the paragraph list that will be pasted into
846                         // the final document. The contents of the inset will be replaced
847                         // by the output of the algorithm below.
848                         pit_type const pit = it.o.pit() - rp.o.from.pit();
849                         pos_type const pos = pit ? it.o.pos() : it.o.pos() - rp.o.from.pos();
850                         inset = pars[pit].getInset(pos);
851                         LASSERT(inset, continue);
852                         diffInset(inset, it);
853                 }
854         }
855         writeToDestBuffer(pars);
856 }
857
858
859 void Compare::Impl::writeToDestBuffer(DocRange const & range,
860         Change::Type type)
861 {
862         ParagraphList pars;
863         getParagraphList(range, pars);
864
865         pos_type size = 0;
866
867         // Set the change
868         ParagraphList::iterator it = pars.begin();
869         for (; it != pars.end(); ++it) {
870                 it->setChange(Change(type));
871                 size += it->size();
872         }
873
874         writeToDestBuffer(pars);
875
876         if (nested_inset_level_ == 0)
877                 compare_.progress(size);
878 }
879
880
881 void Compare::Impl::writeToDestBuffer(ParagraphList const & pars) const
882 {
883         pit_type const pit = dest_pars_->size() - 1;
884         dest_pars_->insert(dest_pars_->end(), pars.begin(), pars.end());
885         if (pit >= 0)
886                 mergeParagraph(dest_buf_->params(), *dest_pars_, pit);
887 }
888
889
890 #include "moc_Compare.cpp"
891
892 } // namespace lyx