3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Vincent van Ravesteijn
8 * Full author contact details are available in file CREDITS.
15 #include "BufferParams.h"
19 #include "insets/InsetText.h"
21 #include "support/lassert.h"
22 #include "support/qstring_helpers.h"
24 #include <boost/next_prior.hpp>
27 using namespace lyx::support;
39 static void step(DocIterator & dit, Direction direction)
41 if (direction == Forward)
42 dit.top().forwardPos();
44 dit.top().backwardPos();
48 static void step(DocIterator & dit, DocIterator const & end, Direction direction)
56 * A pair of two DocIterators that form a range.
60 DocRange(DocIterator from_, DocIterator to_)
61 : from(from_), to(to_)
64 DocRange(Buffer const * buf)
66 from = doc_iterator_begin(buf);
67 to = doc_iterator_end(buf);
72 Text * text() const { return from.text(); }
74 bool empty() const { return to <= from; }
76 size_t length() const;
78 /// The begin of the range
80 /// The end of the range
85 size_t DocRange::length() const
87 ParagraphList const & ps = from.text()->paragraphs();
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();
103 DocPair(DocIterator o_, DocIterator n_)
107 bool operator!=(DocPair const & rhs)
109 // this might not be intuitive but correct for our purpose
110 return o != rhs.o && n != rhs.n;
114 DocPair & operator++()
121 DocPair & operator--()
134 * A pair of two DocRanges.
138 DocRangePair(DocRange o_, DocRange n_)
142 DocRangePair(DocPair from, DocPair to)
143 : o(from.o, to.o), n(from.n, to.n)
146 DocRangePair(Buffer const * o_buf, Buffer const * n_buf)
150 /// Returns the from pair
153 return DocPair(o.from, n.from);
156 /// Returns the to pair
159 return DocPair(o.to, n.to);
167 static DocRangePair stepIntoInset(DocPair const & inset_location)
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();
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.
195 void reset(T const & def)
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_);
213 /// The vector for positive indices
215 /// The vector for negative indices
217 /// The default value that is inserted in the vector
218 /// if more space is needed
224 * The implementation of the algorithm that does the comparison
225 * between two documents.
227 class Compare::Impl {
230 Impl(Compare const & compare)
231 : abort_(false), compare_(compare), recursion_level_(0), D_(0)
238 // Algorithm to find the shortest edit string. This algorithm
239 // only needs a linear amount of memory (linear with the sum
240 // of the number of characters in the two paragraph-lists).
241 bool diff(Buffer const * new_buf, Buffer const * old_buf,
242 Buffer const * dest_buf);
244 /// Set to true to cancel the algorithm
251 status += toqstr("recursion level:") + " " + QString::number(recursion_level_)
252 + " " + toqstr("differences:") + " " + QString::number(D_);
257 /// Finds the middle snake and returns the length of the
258 /// shortest edit script.
259 int findMiddleSnake(DocRangePair const & rp, DocPair & middle_snake);
267 /// Retrieve the middle snake when there is overlap between
268 /// the forward and backward path.
269 SnakeResult retrieveMiddleSnake(int k, int D, Direction direction,
270 DocPair & middle_snake);
272 /// Find the furthest reaching D-path (number of horizontal
273 /// and vertical steps; differences between the old and new
274 /// document) in the k-diagonal (vertical minus horizontal steps).
275 void furthestDpathKdiagonal(int D, int k,
276 DocRangePair const & rp, Direction direction);
278 /// Is there overlap between the forward and backward path
279 bool overlap(int k, int D);
281 /// This function is called recursively by a divide and conquer
282 /// algorithm. Each time, the string is divided into two split
283 /// around the middle snake.
284 void diff_i(DocRangePair const & rp);
286 /// Processes the split chunks. It either adds them as deleted,
287 /// as added, or call diff_i for further processing.
288 void diffPart(DocRangePair const & rp);
290 /// Runs the algorithm for the inset located at /c it and /c it_n
291 /// and adds the result to /c pars.
292 void diffInset(Inset * inset, DocPair const & p);
294 /// Adds the snake to the destination buffer. The algorithm will
295 /// recursively be applied to any InsetTexts that are within the snake.
296 void processSnake(DocRangePair const & rp);
298 /// Writes the range to the destination buffer
299 void writeToDestBuffer(DocRange const & range,
300 Change::Type type = Change::UNCHANGED);
302 /// Writes the paragraph list to the destination buffer
303 void writeToDestBuffer(ParagraphList const & copy_pars) const;
305 /// The length of the old chunk currently processed
307 /// The length of the new chunk currently processed
309 /// The offset diagonal of the reverse path of the
310 /// currently processed chunk
311 int offset_reverse_diagonal_;
312 /// Is the offset odd or even ?
315 /// The thread object, used to emit signals to the GUI
316 Compare const & compare_;
318 /// The buffer containing text that will be marked as old
319 Buffer const * old_buf_;
320 /// The buffer containing text that will be marked as new
321 Buffer const * new_buf_;
322 /// The buffer containing text that will be marked as new
323 Buffer const * dest_buf_;
325 /// The paragraph list of the destination buffer
326 ParagraphList * dest_pars_;
328 /// The level of recursion
329 int recursion_level_;
331 /// The number of nested insets at this level
332 int nested_inset_level_;
334 /// The position/snake in the old/new document
335 /// of the forward/reverse search
336 compl_vector<DocIterator> ofp;
337 compl_vector<DocIterator> nfp;
338 compl_vector<DocIterator> ofs;
339 compl_vector<DocIterator> nfs;
340 compl_vector<DocIterator> orp;
341 compl_vector<DocIterator> nrp;
342 compl_vector<DocIterator> ors;
343 compl_vector<DocIterator> nrs;
345 /// The number of differences in the path the algorithm
346 /// is currently processing.
350 /////////////////////////////////////////////////////////////////////
354 /////////////////////////////////////////////////////////////////////
356 Compare::Compare(Buffer const * new_buf, Buffer const * old_buf,
357 Buffer * const dest_buf, CompareOptions const & options)
358 : new_buffer(new_buf), old_buffer(old_buf), dest_buffer(dest_buf),
359 options_(options), pimpl_(new Impl(*this))
361 connect(&status_timer_, SIGNAL(timeout()),
362 this, SLOT(doStatusMessage()));
363 status_timer_.start(1000);
367 void Compare::doStatusMessage()
369 statusMessage(pimpl_->status());
375 if (!dest_buffer || !new_buffer || !old_buffer)
378 // Copy the buffer params to the new buffer
379 dest_buffer->params() = options_.settings_from_new
380 ? new_buffer->params() : old_buffer->params();
388 finished(pimpl_->abort_);
393 int Compare::doCompare()
395 return pimpl_->diff(new_buffer, old_buffer, dest_buffer);
399 void Compare::abort()
401 pimpl_->abort_ = true;
402 condition_.wakeOne();
404 pimpl_->abort_ = false;
408 static void getParagraphList(DocRange const & range,
409 ParagraphList & pars)
411 // Clone the paragraphs within the selection.
412 pit_type startpit = range.from.pit();
413 pit_type endpit = range.to.pit();
414 ParagraphList const & ps_ = range.text()->paragraphs();
415 ParagraphList tmp_pars(boost::next(ps_.begin(), startpit),
416 boost::next(ps_.begin(), endpit + 1));
418 // Remove the end of the last paragraph; afterwards, remove the
419 // beginning of the first paragraph. Keep this order - there may only
421 Paragraph & back = tmp_pars.back();
422 back.eraseChars(range.to.pos(), back.size(), false);
423 Paragraph & front = tmp_pars.front();
424 front.eraseChars(0, range.from.pos(), false);
426 pars.insert(pars.begin(), tmp_pars.begin(), tmp_pars.end());
430 static bool equal(Inset const * i_o, Inset const * i_n)
435 // Different types of insets
436 if (i_o->lyxCode() != i_n->lyxCode())
439 // Editable insets are assumed to be the same as they are of the
440 // same type. If we later on decide that we insert them in the
441 // document as being unchanged, we will run the algorithm on the
442 // contents of the two insets.
443 // FIXME: This fails if the parameters of the insets differ.
444 // FIXME: We do not recurse into InsetTabulars.
445 // FIXME: We need methods inset->equivalent(inset).
446 if (i_o->editable() && !i_o->asInsetMath()
447 && i_o->asInsetText())
454 return o_os.str() == n_os.str();
458 static bool equal(DocIterator & o, DocIterator & n)
460 // Explicitly check for this, so we won't call
461 // Paragraph::getChar for the last pos.
462 bool const o_lastpos = o.pos() == o.lastpos();
463 bool const n_lastpos = n.pos() == n.lastpos();
464 if (o_lastpos || n_lastpos)
465 return o_lastpos && n_lastpos;
467 Paragraph const & old_par = o.text()->getPar(o.pit());
468 Paragraph const & new_par = n.text()->getPar(n.pit());
470 char_type const c_o = old_par.getChar(o.pos());
471 char_type const c_n = new_par.getChar(n.pos());
475 if (old_par.isInset(o.pos())) {
476 Inset const * i_o = old_par.getInset(o.pos());
477 Inset const * i_n = new_par.getInset(n.pos());
480 return equal(i_o, i_n);
483 Font fo = old_par.getFontSettings(o.buffer()->params(), o.pos());
484 Font fn = new_par.getFontSettings(n.buffer()->params(), n.pos());
489 /// Traverses a snake in a certain direction. p points to a
490 /// position in the old and new file and they are synchronously
491 /// moved along the snake. The function returns true if a snake
493 static bool traverseSnake(DocPair & p, DocRangePair const & range,
497 DocPair const & p_end =
498 direction == Forward ? range.to() : range.from();
501 if (direction == Backward)
503 if (!equal(p.o, p.n)) {
504 if (direction == Backward)
508 if (direction == Forward)
516 /////////////////////////////////////////////////////////////////////
520 /////////////////////////////////////////////////////////////////////
523 void Compare::Impl::furthestDpathKdiagonal(int D, int k,
524 DocRangePair const & rp, Direction direction)
526 compl_vector<DocIterator> & op = direction == Forward ? ofp : orp;
527 compl_vector<DocIterator> & np = direction == Forward ? nfp : nrp;
528 compl_vector<DocIterator> & os = direction == Forward ? ofs : ors;
529 compl_vector<DocIterator> & ns = direction == Forward ? nfs : nrs;
531 // A vertical step means stepping one character in the new document.
532 bool vertical_step = k == -D;
533 if (!vertical_step && k != D) {
534 vertical_step = direction == Forward
535 ? op[k - 1] < op[k + 1] : op[k - 1] > op[k + 1];
538 // Where do we take the step from ?
539 int const kk = vertical_step ? k + 1 : k - 1;
540 DocPair p(op[kk], np[kk]);
541 DocPair const s(os[kk], ns[kk]);
543 // If D==0 we simulate a vertical step from (0,-1) by doing nothing.
546 if (vertical_step && direction == Forward)
547 step(p.n, rp.n.to, direction);
548 else if (vertical_step && direction == Backward)
549 step(p.n, rp.n.from, direction);
550 else if (!vertical_step && direction == Forward)
551 step(p.o, rp.o.to, direction);
552 else if (!vertical_step && direction == Backward)
553 step(p.o, rp.o.from, direction);
557 if (traverseSnake(p, rp, direction)) {
562 // Copy last snake from the previous step
567 //Record new position
573 bool Compare::Impl::overlap(int k, int D)
575 // To generalize for the forward and reverse checks
576 int kk = offset_reverse_diagonal_ - k;
578 // Can we have overlap ?
579 if (kk <= D && kk >= -D) {
580 // Do we have overlap ?
582 return ofp[k] >= orp[kk] && nfp[k] >= nrp[kk];
584 return ofp[kk] >= orp[k] && nfp[kk] >= nrp[k];
590 Compare::Impl::SnakeResult Compare::Impl::retrieveMiddleSnake(
591 int k, int D, Direction direction, DocPair & middle_snake)
593 compl_vector<DocIterator> & os = direction == Forward ? ofs : ors;
594 compl_vector<DocIterator> & ns = direction == Forward ? nfs : nrs;
595 compl_vector<DocIterator> & os_r = direction == Forward ? ors : ofs;
596 compl_vector<DocIterator> & ns_r = direction == Forward ? nrs : nfs;
598 // The diagonal while doing the backward search
599 int kk = -k + offset_reverse_diagonal_;
601 // Did we find a snake ?
602 if (os[k].empty() && os_r[kk].empty()) {
603 // No, there is no snake at all, in which case
604 // the length of the shortest edit script is M+N.
605 LATTEST(2 * D - odd_offset_ == M_ + N_);
610 // Yes, but there is only 1 snake and we found it in the
612 middle_snake.o = os_r[kk];
613 middle_snake.n = ns_r[kk];
617 middle_snake.o = os[k];
618 middle_snake.n = ns[k];
623 int Compare::Impl::findMiddleSnake(DocRangePair const & rp,
624 DocPair & middle_snake)
626 // The lengths of the old and new chunks.
630 // Forward paths are centered around the 0-diagonal; reverse paths
631 // are centered around the diagonal N - M. (Delta in the article)
632 offset_reverse_diagonal_ = N_ - M_;
634 // If the offset is odd, only check for overlap while extending forward
635 // paths, otherwise only check while extending reverse paths.
636 odd_offset_ = (offset_reverse_diagonal_ % 2 != 0);
638 ofp.reset(rp.o.from);
639 nfp.reset(rp.n.from);
640 ofs.reset(DocIterator());
641 nfs.reset(DocIterator());
644 ors.reset(DocIterator());
645 nrs.reset(DocIterator());
647 // In the formula below, the "+ 1" ensures we round like ceil()
648 int const D_max = (M_ + N_ + 1)/2;
649 // D is the number of horizontal and vertical steps, i.e.
650 // different characters in the old and new chunk.
651 for (int D = 0; D <= D_max; ++D) {
652 // to be used in the status messages
655 // Forward and reverse paths
656 for (int f = 0; f < 2; ++f) {
657 Direction direction = f == 0 ? Forward : Backward;
659 // Diagonals between -D and D can be reached by a D-path
660 for (int k = -D; k <= D; k += 2) {
661 // Find the furthest reaching D-path on this diagonal
662 furthestDpathKdiagonal(D, k, rp, direction);
664 // Only check for overlap for forward paths if the offset is odd
665 // and only for reverse paths if the offset is even.
666 if (odd_offset_ == (direction == Forward)) {
668 // Do the forward and backward paths overlap ?
669 if (overlap(k, D - odd_offset_)) {
670 retrieveMiddleSnake(k, D, direction, middle_snake);
671 return 2 * D - odd_offset_;
679 // This should never be reached
684 bool Compare::Impl::diff(Buffer const * new_buf, Buffer const * old_buf,
685 Buffer const * dest_buf)
687 if (!new_buf || !old_buf || !dest_buf)
692 dest_buf_ = dest_buf;
693 dest_pars_ = &dest_buf->inset().asInsetText()->paragraphs();
696 recursion_level_ = 0;
697 nested_inset_level_ = 0;
699 DocRangePair rp(old_buf_, new_buf_);
701 DocPair from = rp.from();
702 traverseSnake(from, rp, Forward);
703 DocRangePair const snake(rp.from(), from);
706 // Start the recursive algorithm
707 DocRangePair rp_new(from, rp.to());
708 if (!rp_new.o.empty() || !rp_new.n.empty())
711 for (pit_type p = 0; p < (pit_type)dest_pars_->size(); ++p) {
712 (*dest_pars_)[p].setBuffer(const_cast<Buffer &>(*dest_buf));
713 (*dest_pars_)[p].setInsetOwner(&dest_buf_->inset());
720 void Compare::Impl::diff_i(DocRangePair const & rp)
726 DocPair middle_snake;
728 // Divides the problem into two smaller problems, split around
729 // the snake in the middle.
730 int const L_ses = findMiddleSnake(rp, middle_snake);
732 // Set maximum of progress bar
733 if (++recursion_level_ == 1)
734 compare_.progressMax(L_ses);
736 // There are now three possibilities: the strings were the same,
737 // the strings were completely different, or we found a middle
738 // snake and we can split the string into two parts to process.
740 // Two the same strings (this must be a very rare case, because
741 // usually this will be part of a snake adjacent to these strings).
742 writeToDestBuffer(rp.o);
744 else if (middle_snake.o.empty()) {
745 // Two totally different strings
746 writeToDestBuffer(rp.o, Change::DELETED);
747 writeToDestBuffer(rp.n, Change::INSERTED);
750 // Retrieve the complete snake
751 DocPair first_part_end = middle_snake;
752 traverseSnake(first_part_end, rp, Backward);
753 DocRangePair first_part(rp.from(), first_part_end);
755 DocPair second_part_begin = middle_snake;
756 traverseSnake(second_part_begin, rp, Forward);
757 DocRangePair second_part(second_part_begin, rp.to());
759 // Split the string in three parts:
760 // 1. in front of the snake
761 diffPart(first_part);
763 // 2. the snake itself, and
764 DocRangePair const snake(first_part.to(), second_part.from());
767 // 3. behind the snake.
768 diffPart(second_part);
774 void Compare::Impl::diffPart(DocRangePair const & rp)
776 // Is there a finite length string in both buffers, if not there
777 // is an empty string and we write the other one to the buffer.
778 if (!rp.o.empty() && !rp.n.empty())
781 else if (!rp.o.empty())
782 writeToDestBuffer(rp.o, Change::DELETED);
784 else if (!rp.n.empty())
785 writeToDestBuffer(rp.n, Change::INSERTED);
789 void Compare::Impl::diffInset(Inset * inset, DocPair const & p)
791 // Find the dociterators for the beginning and the
792 // end of the inset, for the old and new document.
793 DocRangePair const rp = stepIntoInset(p);
795 // Recurse into the inset. Temporarily replace the dest_pars
796 // paragraph list by the paragraph list of the nested inset.
797 ParagraphList * backup_dest_pars = dest_pars_;
798 dest_pars_ = &inset->asInsetText()->text().paragraphs();
801 ++nested_inset_level_;
803 --nested_inset_level_;
805 dest_pars_ = backup_dest_pars;
809 void Compare::Impl::processSnake(DocRangePair const & rp)
812 getParagraphList(rp.o, pars);
814 // Find insets in this paragaph list
815 DocPair it = rp.from();
816 for (; it.o < rp.o.to; ++it) {
817 Inset * inset = it.o.text()->getPar(it.o.pit()).getInset(it.o.pos());
818 if (inset && inset->editable() && inset->asInsetText()) {
819 // Find the inset in the paragraph list that will be pasted into
820 // the final document. The contents of the inset will be replaced
821 // by the output of the algorithm below.
822 pit_type const pit = it.o.pit() - rp.o.from.pit();
823 pos_type const pos = pit ? it.o.pos() : it.o.pos() - rp.o.from.pos();
824 inset = pars[pit].getInset(pos);
825 LASSERT(inset, continue);
826 diffInset(inset, it);
829 writeToDestBuffer(pars);
833 void Compare::Impl::writeToDestBuffer(DocRange const & range,
837 getParagraphList(range, pars);
842 ParagraphList::iterator it = pars.begin();
843 for (; it != pars.end(); ++it) {
844 it->setChange(Change(type));
848 writeToDestBuffer(pars);
850 if (nested_inset_level_ == 0)
851 compare_.progress(size);
855 void Compare::Impl::writeToDestBuffer(ParagraphList const & pars) const
857 pit_type const pit = dest_pars_->size() - 1;
858 dest_pars_->insert(dest_pars_->end(), pars.begin(), pars.end());
860 mergeParagraph(dest_buf_->params(), *dest_pars_, pit);
864 #include "moc_Compare.cpp"