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.
16 #include "BufferParams.h"
20 #include "insets/InsetText.h"
22 #include "support/lassert.h"
23 #include "support/lyxalgo.h"
24 #include "support/qstring_helpers.h"
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 const & from_, DocIterator const & to_)
61 : from(from_), to(to_)
64 DocRange(Buffer const * buf) :
65 from(doc_iterator_begin(buf)),
66 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 const & o_, DocRange const & n_)
142 DocRangePair(DocPair const & from, DocPair const & 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), 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)
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);
247 /// Set to true to cancel the algorithm
254 status += toqstr("recursion level:") + " " + QString::number(recursion_level_)
255 + " " + toqstr("differences:") + " " + QString::number(D_);
260 /// Finds the middle snake and returns the length of the
261 /// shortest edit script.
262 int findMiddleSnake(DocRangePair const & rp, DocPair & middle_snake);
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);
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);
281 /// Is there overlap between the forward and backward path
282 bool overlap(int k, int D);
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);
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);
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);
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);
301 /// Writes the range to the destination buffer
302 void writeToDestBuffer(DocRange const & range,
303 Change::Type type = Change::UNCHANGED);
305 /// Writes the paragraph list to the destination buffer
306 void writeToDestBuffer(ParagraphList const & copy_pars) const;
308 /// The length of the old chunk currently processed
310 /// The length of the new chunk currently processed
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 ?
318 /// The thread object, used to emit signals to the GUI
319 Compare const & compare_;
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_;
328 /// The paragraph list of the destination buffer
329 ParagraphList * dest_pars_;
331 /// The level of recursion
332 int recursion_level_;
334 /// The number of nested insets at this level
335 int nested_inset_level_;
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;
348 /// The number of differences in the path the algorithm
349 /// is currently processing.
353 /////////////////////////////////////////////////////////////////////
357 /////////////////////////////////////////////////////////////////////
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))
364 connect(&status_timer_, SIGNAL(timeout()),
365 this, SLOT(doStatusMessage()));
366 status_timer_.start(1000);
370 void Compare::doStatusMessage()
372 statusMessage(pimpl_->status());
378 if (!dest_buffer || !new_buffer || !old_buffer)
381 // Copy the buffer params to the destination buffer
382 dest_buffer->params() = options_.settings_from_new
383 ? new_buffer->params() : old_buffer->params();
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);
398 finished(pimpl_->abort_);
403 int Compare::doCompare()
405 return pimpl_->diff(new_buffer, old_buffer, dest_buffer);
409 void Compare::abort()
411 pimpl_->abort_ = true;
412 condition_.wakeOne();
414 pimpl_->abort_ = false;
418 static void getParagraphList(DocRange const & range,
419 ParagraphList & pars)
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));
428 // Remove the end of the last paragraph; afterwards, remove the
429 // beginning of the first paragraph. Keep this order - there may only
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);
436 pars.insert(pars.begin(), tmp_pars.begin(), tmp_pars.end());
440 static bool equal(Inset const * i_o, Inset const * i_n)
445 // Different types of insets
446 if (i_o->lyxCode() != i_n->lyxCode())
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())
464 return o_os.str() == n_os.str();
468 static bool equal(DocIterator & o, DocIterator & n)
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;
477 Paragraph const & old_par = o.text()->getPar(o.pit());
478 Paragraph const & new_par = n.text()->getPar(n.pit());
480 char_type const c_o = old_par.getChar(o.pos());
481 char_type const c_n = new_par.getChar(n.pos());
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());
490 return equal(i_o, i_n);
493 Font fo = old_par.getFontSettings(o.buffer()->params(), o.pos());
494 Font fn = new_par.getFontSettings(n.buffer()->params(), n.pos());
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
503 static bool traverseSnake(DocPair & p, DocRangePair const & range,
507 DocPair const & p_end =
508 direction == Forward ? range.to() : range.from();
511 if (direction == Backward)
513 if (!equal(p.o, p.n)) {
514 if (direction == Backward)
518 if (direction == Forward)
526 /////////////////////////////////////////////////////////////////////
530 /////////////////////////////////////////////////////////////////////
533 void Compare::Impl::furthestDpathKdiagonal(int D, int k,
534 DocRangePair const & rp, Direction direction)
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;
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];
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]);
553 // If D==0 we simulate a vertical step from (0,-1) by doing nothing.
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);
567 if (traverseSnake(p, rp, direction)) {
572 // Copy last snake from the previous step
577 //Record new position
583 bool Compare::Impl::overlap(int k, int D)
585 // To generalize for the forward and reverse checks
586 int kk = offset_reverse_diagonal_ - k;
588 // Can we have overlap ?
589 if (kk <= D && kk >= -D) {
590 // Do we have overlap ?
592 return ofp[k] >= orp[kk] && nfp[k] >= nrp[kk];
594 return ofp[kk] >= orp[k] && nfp[kk] >= nrp[k];
600 Compare::Impl::SnakeResult Compare::Impl::retrieveMiddleSnake(
601 int k, int D, Direction direction, DocPair & middle_snake)
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;
608 // The diagonal while doing the backward search
609 int kk = -k + offset_reverse_diagonal_;
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_);
620 // Yes, but there is only 1 snake and we found it in the
622 middle_snake.o = os_r[kk];
623 middle_snake.n = ns_r[kk];
627 middle_snake.o = os[k];
628 middle_snake.n = ns[k];
633 int Compare::Impl::findMiddleSnake(DocRangePair const & rp,
634 DocPair & middle_snake)
636 // The lengths of the old and new chunks.
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_;
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);
648 ofp.reset(rp.o.from);
649 nfp.reset(rp.n.from);
650 ofs.reset(DocIterator());
651 nfs.reset(DocIterator());
654 ors.reset(DocIterator());
655 nrs.reset(DocIterator());
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
665 // Forward and reverse paths
666 for (int f = 0; f < 2; ++f) {
667 Direction direction = f == 0 ? Forward : Backward;
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);
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)) {
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_;
689 // This should never be reached
694 bool Compare::Impl::diff(Buffer const * new_buf, Buffer const * old_buf,
695 Buffer const * dest_buf)
697 if (!new_buf || !old_buf || !dest_buf)
702 dest_buf_ = dest_buf;
703 dest_pars_ = &dest_buf->inset().asInsetText()->paragraphs();
706 recursion_level_ = 0;
707 nested_inset_level_ = 0;
709 DocRangePair rp(old_buf_, new_buf_);
711 DocPair from = rp.from();
712 traverseSnake(from, rp, Forward);
713 DocRangePair const snake(rp.from(), from);
716 // Start the recursive algorithm
717 DocRangePair rp_new(from, rp.to());
718 if (!rp_new.o.empty() || !rp_new.n.empty())
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());
730 void Compare::Impl::diff_i(DocRangePair const & rp)
736 DocPair middle_snake;
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);
742 // Set maximum of progress bar
743 if (++recursion_level_ == 1)
744 compare_.progressMax(L_ses);
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.
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);
754 else if (middle_snake.o.empty()) {
755 // Two totally different strings
756 writeToDestBuffer(rp.o, Change::DELETED);
757 writeToDestBuffer(rp.n, Change::INSERTED);
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);
765 DocPair second_part_begin = middle_snake;
766 traverseSnake(second_part_begin, rp, Forward);
767 DocRangePair second_part(second_part_begin, rp.to());
769 // Split the string in three parts:
770 // 1. in front of the snake
771 diffPart(first_part);
773 // 2. the snake itself, and
774 DocRangePair const snake(first_part.to(), second_part.from());
777 // 3. behind the snake.
778 diffPart(second_part);
784 void Compare::Impl::diffPart(DocRangePair const & rp)
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())
791 else if (!rp.o.empty())
792 writeToDestBuffer(rp.o, Change::DELETED);
794 else if (!rp.n.empty())
795 writeToDestBuffer(rp.n, Change::INSERTED);
799 void Compare::Impl::diffInset(Inset * inset, DocPair const & p)
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);
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();
811 ++nested_inset_level_;
813 --nested_inset_level_;
815 dest_pars_ = backup_dest_pars;
819 void Compare::Impl::processSnake(DocRangePair const & rp)
822 getParagraphList(rp.o, pars);
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);
839 writeToDestBuffer(pars);
843 void Compare::Impl::writeToDestBuffer(DocRange const & range,
847 getParagraphList(range, pars);
852 ParagraphList::iterator it = pars.begin();
853 for (; it != pars.end(); ++it) {
854 it->setChange(Change(type));
858 writeToDestBuffer(pars);
860 if (nested_inset_level_ == 0)
861 compare_.progress(size);
865 void Compare::Impl::writeToDestBuffer(ParagraphList const & pars) const
867 pit_type const pit = dest_pars_->size() - 1;
868 dest_pars_->insert(dest_pars_->end(), pars.begin(), pars.end());
870 mergeParagraph(dest_buf_->params(), *dest_pars_, pit);
874 #include "moc_Compare.cpp"