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