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