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();
102 DocPair(DocIterator o_, DocIterator n_)
106 bool operator!=(DocPair const & rhs) {
107 // this might not be intuitive but correct for our purpose
108 return o != rhs.o && n != rhs.n;
112 DocPair & operator++()
119 DocPair & operator--()
132 * A pair of two DocRanges.
136 DocRangePair(DocRange o_, DocRange n_)
140 DocRangePair(DocPair from, DocPair to)
141 : o(from.o, to.o), n(from.n, to.n)
144 DocRangePair(Buffer const * o_buf, Buffer const * n_buf)
148 /// Returns the from pair
149 DocPair from() const { return DocPair(o.from, n.from); }
151 /// Returns the to pair
152 DocPair to() const { return DocPair(o.to, n.to); }
159 static DocRangePair stepIntoInset(DocPair const & inset_location)
161 DocRangePair rp(inset_location, inset_location);
162 rp.o.from.forwardPos();
163 rp.n.from.forwardPos();
164 step(rp.o.to, Forward);
165 step(rp.n.to, Forward);
166 rp.o.to.backwardPos();
167 rp.n.to.backwardPos();
173 * This class is designed to hold a vector that has both positive as
174 * negative indices. It is internally represented as two vectors, one
175 * for non-zero indices and one for negative indices. In this way, the
176 * vector can grow in both directions.
177 * If an index is not available in the vector, the default value is
178 * returned. If an object is put in the vector beyond its size, the
179 * empty spots in between are also filled with the default value.
186 void reset(T const & def)
193 /// Gets the value at index. If it is not in the vector
194 /// the default value is inserted and returned.
195 T & operator[](int index) {
196 vector<T> & V = index >= 0 ? Vp_ : Vn_;
197 unsigned int const ii = index >= 0 ? index : -index - 1;
198 while (ii >= V.size())
199 V.push_back(default_);
204 /// The vector for positive indices
206 /// The vector for negative indices
208 /// The default value that is inserted in the vector
209 /// if more space is needed
215 * The implementation of the algorithm that does the comparison
216 * between two documents.
218 class Compare::Impl {
221 Impl(Compare const & compare)
222 : abort_(false), compare_(compare), recursion_level_(0), D_(0)
228 // Algorithm to find the shortest edit string. This algorithm
229 // only needs a linear amount of memory (linear with the sum
230 // of the number of characters in the two paragraph-lists).
231 bool diff(Buffer const * new_buf, Buffer const * old_buf,
232 Buffer const * dest_buf);
234 /// Set to true to cancel the algorithm
240 status += toqstr("recursion level:") + " " + QString::number(recursion_level_)
241 + " " + toqstr("differences:") + " " + QString::number(D_);
246 /// Finds the middle snake and returns the length of the
247 /// shortest edit script.
248 int findMiddleSnake(DocRangePair const & rp, DocPair & middle_snake);
256 /// Retrieve the middle snake when there is overlap between
257 /// the forward and backward path.
258 SnakeResult retrieveMiddleSnake(int k, int D, Direction direction,
259 DocPair & middle_snake);
261 /// Find the the furthest reaching D-path (number of horizontal
262 /// and vertical steps; differences between the old and new
263 /// document) in the k-diagonal (vertical minus horizontal steps).
264 void furthestDpathKdiagonal(int D, int k,
265 DocRangePair const & rp, Direction direction);
267 /// Is there overlap between the forward and backward path
268 bool overlap(int k, int D);
270 /// This function is called recursively by a divide and conquer
271 /// algorithm. Each time, the string is divided into two split
272 /// around the middle snake.
273 void diff_i(DocRangePair const & rp);
275 /// Processes the splitted chunks. It either adds them as deleted,
276 /// as added, or call diff_i for further processing.
277 void diffPart(DocRangePair const & rp);
279 /// Runs the algorithm for the inset located at /c it and /c it_n
280 /// and adds the result to /c pars.
281 void diffInset(Inset * inset, DocPair const & p);
283 /// Adds the snake to the destination buffer. The algorithm will
284 /// recursively be applied to any InsetTexts that are within the snake.
285 void processSnake(DocRangePair const & rp);
287 /// Writes the range to the destination buffer
288 void writeToDestBuffer(DocRange const & range,
289 Change::Type type = Change::UNCHANGED);
291 /// Writes the paragraph list to the destination buffer
292 void writeToDestBuffer(ParagraphList const & copy_pars) const;
294 /// The length of the old chunk currently processed
296 /// The length of the new chunk currently processed
298 /// The offset diagonal of the reverse path of the
299 /// currently processed chunk
300 int offset_reverse_diagonal_;
301 /// Is the offset odd or even ?
304 /// The thread object, used to emit signals to the GUI
305 Compare const & compare_;
307 /// The buffer containing text that will be marked as old
308 Buffer const * old_buf_;
309 /// The buffer containing text that will be marked as new
310 Buffer const * new_buf_;
311 /// The buffer containing text that will be marked as new
312 Buffer const * dest_buf_;
314 /// The paragraph list of the destination buffer
315 ParagraphList * dest_pars_;
317 /// The level of recursion
318 int recursion_level_;
320 /// The number of nested insets at this level
321 int nested_inset_level_;
323 /// The position/snake in the old/new document
324 /// of the forward/reverse search
325 compl_vector<DocIterator> ofp;
326 compl_vector<DocIterator> nfp;
327 compl_vector<DocIterator> ofs;
328 compl_vector<DocIterator> nfs;
329 compl_vector<DocIterator> orp;
330 compl_vector<DocIterator> nrp;
331 compl_vector<DocIterator> ors;
332 compl_vector<DocIterator> nrs;
334 /// The number of differences in the path the algorithm
335 /// is currently processing.
339 /////////////////////////////////////////////////////////////////////
343 /////////////////////////////////////////////////////////////////////
345 Compare::Compare(Buffer const * new_buf, Buffer const * old_buf,
346 Buffer * const dest_buf, CompareOptions const & options)
347 : new_buffer(new_buf), old_buffer(old_buf), dest_buffer(dest_buf),
348 options_(options), pimpl_(new Impl(*this))
350 connect(&status_timer_, SIGNAL(timeout()),
351 this, SLOT(doStatusMessage()));
352 status_timer_.start(1000);
356 void Compare::doStatusMessage()
358 statusMessage(pimpl_->status());
364 if (!dest_buffer || !new_buffer || !old_buffer)
367 // Copy the buffer params to the new buffer
368 dest_buffer->params() = options_.settings_from_new
369 ? new_buffer->params() : old_buffer->params();
377 finished(pimpl_->abort_);
382 int Compare::doCompare()
384 return pimpl_->diff(new_buffer, old_buffer, dest_buffer);
388 void Compare::abort()
390 pimpl_->abort_ = true;
391 condition_.wakeOne();
393 pimpl_->abort_ = false;
397 static void getParagraphList(DocRange const & range,
398 ParagraphList & pars)
400 // Clone the paragraphs within the selection.
401 pit_type startpit = range.from.pit();
402 pit_type endpit = range.to.pit();
403 ParagraphList const & ps_ = range.text()->paragraphs();
404 ParagraphList tmp_pars(boost::next(ps_.begin(), startpit),
405 boost::next(ps_.begin(), endpit + 1));
407 // Remove the end of the last paragraph; afterwards, remove the
408 // beginning of the first paragraph. Keep this order - there may only
410 Paragraph & back = tmp_pars.back();
411 back.eraseChars(range.to.pos(), back.size(), false);
412 Paragraph & front = tmp_pars.front();
413 front.eraseChars(0, range.from.pos(), false);
415 pars.insert(pars.begin(), tmp_pars.begin(), tmp_pars.end());
419 static bool equal(Inset const * i_o, Inset const * i_n)
424 // Different types of insets
425 if (i_o->lyxCode() != i_n->lyxCode())
428 // Editable insets are assumed to be the same as they are of the
429 // same type. If we later on decide that we insert them in the
430 // document as being unchanged, we will run the algorithm on the
431 // contents of the two insets.
432 // FIXME: This fails if the parameters of the insets differ.
433 // FIXME: We do not recurse into InsetTabulars.
434 // FIXME: We need methods inset->equivalent(inset).
435 if (i_o->editable() && !i_o->asInsetMath()
436 && i_o->asInsetText())
443 return o_os.str() == n_os.str();
447 static bool equal(DocIterator & o, DocIterator & n) {
448 // Explicitly check for this, so we won't call
449 // Paragraph::getChar for the last pos.
450 bool const o_lastpos = o.pos() == o.lastpos();
451 bool const n_lastpos = n.pos() == n.lastpos();
452 if (o_lastpos || n_lastpos)
453 return o_lastpos && n_lastpos;
455 Paragraph const & old_par = o.text()->getPar(o.pit());
456 Paragraph const & new_par = n.text()->getPar(n.pit());
458 char_type const c_o = old_par.getChar(o.pos());
459 char_type const c_n = new_par.getChar(n.pos());
463 if (old_par.isInset(o.pos())) {
464 Inset const * i_o = old_par.getInset(o.pos());
465 Inset const * i_n = new_par.getInset(n.pos());
468 return equal(i_o, i_n);
471 Font fo = old_par.getFontSettings(o.buffer()->params(), o.pos());
472 Font fn = new_par.getFontSettings(n.buffer()->params(), n.pos());
477 /// Traverses a snake in a certain direction. p points to a
478 /// position in the old and new file and they are synchronously
479 /// moved along the snake. The function returns true if a snake
481 static bool traverseSnake(DocPair & p, DocRangePair const & range,
485 DocPair const & p_end =
486 direction == Forward ? range.to() : range.from();
489 if (direction == Backward)
491 if (!equal(p.o, p.n)) {
492 if (direction == Backward)
496 if (direction == Forward)
504 /////////////////////////////////////////////////////////////////////
508 /////////////////////////////////////////////////////////////////////
511 void Compare::Impl::furthestDpathKdiagonal(int D, int k,
512 DocRangePair const & rp, Direction direction)
514 compl_vector<DocIterator> & op = direction == Forward ? ofp : orp;
515 compl_vector<DocIterator> & np = direction == Forward ? nfp : nrp;
516 compl_vector<DocIterator> & os = direction == Forward ? ofs : ors;
517 compl_vector<DocIterator> & ns = direction == Forward ? nfs : nrs;
519 // A vertical step means stepping one character in the new document.
520 bool vertical_step = k == -D;
521 if (!vertical_step && k != D) {
522 vertical_step = direction == Forward
523 ? op[k - 1] < op[k + 1] : op[k - 1] > op[k + 1];
526 // Where do we take the step from ?
527 int const kk = vertical_step ? k + 1 : k - 1;
528 DocPair p(op[kk], np[kk]);
529 DocPair const s(os[kk], ns[kk]);
531 // If D==0 we simulate a vertical step from (0,-1) by doing nothing.
534 if (vertical_step && direction == Forward)
535 step(p.n, rp.n.to, direction);
536 else if (vertical_step && direction == Backward)
537 step(p.n, rp.n.from, direction);
538 else if (!vertical_step && direction == Forward)
539 step(p.o, rp.o.to, direction);
540 else if (!vertical_step && direction == Backward)
541 step(p.o, rp.o.from, direction);
545 if (traverseSnake(p, rp, direction)) {
550 // Copy last snake from the previous step
555 //Record new position
561 bool Compare::Impl::overlap(int k, int D)
563 // To generalize for the forward and reverse checks
564 int kk = offset_reverse_diagonal_ - k;
566 // Can we have overlap ?
567 if (kk <= D && kk >= -D) {
568 // Do we have overlap ?
570 return ofp[k] >= orp[kk] && nfp[k] >= nrp[kk];
572 return ofp[kk] >= orp[k] && nfp[kk] >= nrp[k];
578 Compare::Impl::SnakeResult Compare::Impl::retrieveMiddleSnake(
579 int k, int D, Direction direction, DocPair & middle_snake)
581 compl_vector<DocIterator> & os = direction == Forward ? ofs : ors;
582 compl_vector<DocIterator> & ns = direction == Forward ? nfs : nrs;
583 compl_vector<DocIterator> & os_r = direction == Forward ? ors : ofs;
584 compl_vector<DocIterator> & ns_r = direction == Forward ? nrs : nfs;
586 // The diagonal while doing the backward search
587 int kk = -k + offset_reverse_diagonal_;
589 // Did we find a snake ?
590 if (os[k].empty() && os_r[kk].empty()) {
591 // No, there is no snake at all, in which case
592 // the length of the shortest edit script is M+N.
593 LASSERT(2 * D - odd_offset_ == M_ + N_, /**/);
598 // Yes, but there is only 1 snake and we found it in the
600 middle_snake.o = os_r[kk];
601 middle_snake.n = ns_r[kk];
605 middle_snake.o = os[k];
606 middle_snake.n = ns[k];
611 int Compare::Impl::findMiddleSnake(DocRangePair const & rp,
612 DocPair & middle_snake)
614 // The lengths of the old and new chunks.
618 // Forward paths are centered around the 0-diagonal; reverse paths
619 // are centered around the diagonal N - M. (Delta in the article)
620 offset_reverse_diagonal_ = N_ - M_;
622 // If the offset is odd, only check for overlap while extending forward
623 // paths, otherwise only check while extending reverse paths.
624 odd_offset_ = (offset_reverse_diagonal_ % 2 != 0);
626 ofp.reset(rp.o.from);
627 nfp.reset(rp.n.from);
628 ofs.reset(DocIterator());
629 nfs.reset(DocIterator());
632 ors.reset(DocIterator());
633 nrs.reset(DocIterator());
635 // In the formula below, the "+ 1" ensures we round like ceil()
636 int const D_max = (M_ + N_ + 1)/2;
637 // D is the number of horizontal and vertical steps, i.e.
638 // different characters in the old and new chunk.
639 for (int D = 0; D <= D_max; ++D) {
640 // to be used in the status messages
643 // Forward and reverse paths
644 for (int f = 0; f < 2; ++f) {
645 Direction direction = f == 0 ? Forward : Backward;
647 // Diagonals between -D and D can be reached by a D-path
648 for (int k = -D; k <= D; k += 2) {
649 // Find the furthest reaching D-path on this diagonal
650 furthestDpathKdiagonal(D, k, rp, direction);
652 // Only check for overlap for forward paths if the offset is odd
653 // and only for reverse paths if the offset is even.
654 if (odd_offset_ == (direction == Forward)) {
656 // Do the forward and backward paths overlap ?
657 if (overlap(k, D - odd_offset_)) {
658 retrieveMiddleSnake(k, D, direction, middle_snake);
659 return 2 * D - odd_offset_;
667 // This should never be reached
672 bool Compare::Impl::diff(Buffer const * new_buf, Buffer const * old_buf,
673 Buffer const * dest_buf)
675 if (!new_buf || !old_buf || !dest_buf)
680 dest_buf_ = dest_buf;
681 dest_pars_ = &dest_buf->inset().asInsetText()->paragraphs();
684 recursion_level_ = 0;
685 nested_inset_level_ = 0;
687 DocRangePair rp(old_buf_, new_buf_);
689 DocPair from = rp.from();
690 traverseSnake(from, rp, Forward);
691 DocRangePair const snake(rp.from(), from);
694 // Start the recursive algorithm
695 DocRangePair rp_new(from, rp.to());
696 if (!rp_new.o.empty() || !rp_new.n.empty())
699 for (pit_type p = 0; p < (pit_type)dest_pars_->size(); ++p) {
700 (*dest_pars_)[p].setBuffer(const_cast<Buffer &>(*dest_buf));
701 (*dest_pars_)[p].setInsetOwner(&dest_buf_->inset());
708 void Compare::Impl::diff_i(DocRangePair const & rp)
714 DocPair middle_snake;
716 // Divides the problem into two smaller problems, split around
717 // the snake in the middle.
718 int const L_ses = findMiddleSnake(rp, middle_snake);
720 // Set maximum of progress bar
721 if (++recursion_level_ == 1)
722 compare_.progressMax(L_ses);
724 // There are now three possibilities: the strings were the same,
725 // the strings were completely different, or we found a middle
726 // snake and we can split the string into two parts to process.
728 // Two the same strings (this must be a very rare case, because
729 // usually this will be part of a snake adjacent to these strings).
730 writeToDestBuffer(rp.o);
732 else if (middle_snake.o.empty()) {
733 // Two totally different strings
734 writeToDestBuffer(rp.o, Change::DELETED);
735 writeToDestBuffer(rp.n, Change::INSERTED);
738 // Retrieve the complete snake
739 DocPair first_part_end = middle_snake;
740 traverseSnake(first_part_end, rp, Backward);
741 DocRangePair first_part(rp.from(), first_part_end);
743 DocPair second_part_begin = middle_snake;
744 traverseSnake(second_part_begin, rp, Forward);
745 DocRangePair second_part(second_part_begin, rp.to());
747 // Split the string in three parts:
748 // 1. in front of the snake
749 diffPart(first_part);
751 // 2. the snake itself, and
752 DocRangePair const snake(first_part.to(), second_part.from());
755 // 3. behind the snake.
756 diffPart(second_part);
762 void Compare::Impl::diffPart(DocRangePair const & rp)
764 // Is there a finite length string in both buffers, if not there
765 // is an empty string and we write the other one to the buffer.
766 if (!rp.o.empty() && !rp.n.empty())
769 else if (!rp.o.empty())
770 writeToDestBuffer(rp.o, Change::DELETED);
772 else if (!rp.n.empty())
773 writeToDestBuffer(rp.n, Change::INSERTED);
777 void Compare::Impl::diffInset(Inset * inset, DocPair const & p)
779 // Find the dociterators for the beginning and the
780 // end of the inset, for the old and new document.
781 DocRangePair const rp = stepIntoInset(p);
783 // Recurse into the inset. Temporarily replace the dest_pars
784 // paragraph list by the paragraph list of the nested inset.
785 ParagraphList * backup_dest_pars = dest_pars_;
786 dest_pars_ = &inset->asInsetText()->text().paragraphs();
789 ++nested_inset_level_;
791 --nested_inset_level_;
793 dest_pars_ = backup_dest_pars;
797 void Compare::Impl::processSnake(DocRangePair const & rp)
800 getParagraphList(rp.o, pars);
802 // Find insets in this paragaph list
803 DocPair it = rp.from();
804 for (; it.o < rp.o.to; ++it) {
805 Inset * inset = it.o.text()->getPar(it.o.pit()).getInset(it.o.pos());
806 if (inset && inset->editable() && inset->asInsetText()) {
807 // Find the inset in the paragraph list that will be pasted into
808 // the final document. The contents of the inset will be replaced
809 // by the output of the algorithm below.
810 pit_type const pit = it.o.pit() - rp.o.from.pit();
811 pos_type const pos = pit ? it.o.pos() : it.o.pos() - rp.o.from.pos();
812 inset = pars[pit].getInset(pos);
813 LASSERT(inset, /**/);
814 diffInset(inset, it);
817 writeToDestBuffer(pars);
821 void Compare::Impl::writeToDestBuffer(DocRange const & range,
825 getParagraphList(range, pars);
830 ParagraphList::iterator it = pars.begin();
831 for (; it != pars.end(); ++it) {
832 it->setChange(Change(type));
836 writeToDestBuffer(pars);
838 if (nested_inset_level_ == 0)
839 compare_.progress(size);
843 void Compare::Impl::writeToDestBuffer(ParagraphList const & pars) const
845 pit_type const pit = dest_pars_->size() - 1;
846 dest_pars_->insert(dest_pars_->end(), pars.begin(), pars.end());
848 mergeParagraph(dest_buf_->params(), *dest_pars_, pit);
852 #include "moc_Compare.cpp"