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