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/qstring_helpers.h"
25 #include <boost/next_prior.hpp>
28 using namespace lyx::support;
40 static void step(DocIterator & dit, Direction direction)
42 if (direction == Forward)
43 dit.top().forwardPos();
45 dit.top().backwardPos();
49 static void step(DocIterator & dit, DocIterator const & end, Direction direction)
57 * A pair of two DocIterators that form a range.
61 DocRange(DocIterator from_, DocIterator to_)
62 : from(from_), to(to_)
65 DocRange(Buffer const * buf)
67 from = doc_iterator_begin(buf);
68 to = doc_iterator_end(buf);
73 Text * text() const { return from.text(); }
75 bool empty() const { return to <= from; }
77 size_t length() const;
79 /// The begin of the range
81 /// The end of the range
86 size_t DocRange::length() const
88 ParagraphList const & ps = from.text()->paragraphs();
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();
104 DocPair(DocIterator o_, DocIterator n_)
108 bool operator!=(DocPair const & rhs)
110 // this might not be intuitive but correct for our purpose
111 return o != rhs.o && n != rhs.n;
115 DocPair & operator++()
122 DocPair & operator--()
135 * A pair of two DocRanges.
139 DocRangePair(DocRange o_, DocRange n_)
143 DocRangePair(DocPair from, DocPair to)
144 : o(from.o, to.o), n(from.n, to.n)
147 DocRangePair(Buffer const * o_buf, Buffer const * n_buf)
151 /// Returns the from pair
154 return DocPair(o.from, n.from);
157 /// Returns the to pair
160 return DocPair(o.to, n.to);
168 static DocRangePair stepIntoInset(DocPair const & inset_location)
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();
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.
196 void reset(T const & def)
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_);
214 /// The vector for positive indices
216 /// The vector for negative indices
218 /// The default value that is inserted in the vector
219 /// if more space is needed
225 * The implementation of the algorithm that does the comparison
226 * between two documents.
228 class Compare::Impl {
231 Impl(Compare const & compare)
232 : abort_(false), compare_(compare), recursion_level_(0), D_(0)
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);
245 /// Set to true to cancel the algorithm
252 status += toqstr("recursion level:") + " " + QString::number(recursion_level_)
253 + " " + toqstr("differences:") + " " + QString::number(D_);
258 /// Finds the middle snake and returns the length of the
259 /// shortest edit script.
260 int findMiddleSnake(DocRangePair const & rp, DocPair & middle_snake);
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);
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);
279 /// Is there overlap between the forward and backward path
280 bool overlap(int k, int D);
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);
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);
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);
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);
299 /// Writes the range to the destination buffer
300 void writeToDestBuffer(DocRange const & range,
301 Change::Type type = Change::UNCHANGED);
303 /// Writes the paragraph list to the destination buffer
304 void writeToDestBuffer(ParagraphList const & copy_pars) const;
306 /// The length of the old chunk currently processed
308 /// The length of the new chunk currently processed
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 ?
316 /// The thread object, used to emit signals to the GUI
317 Compare const & compare_;
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_;
326 /// The paragraph list of the destination buffer
327 ParagraphList * dest_pars_;
329 /// The level of recursion
330 int recursion_level_;
332 /// The number of nested insets at this level
333 int nested_inset_level_;
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;
346 /// The number of differences in the path the algorithm
347 /// is currently processing.
351 /////////////////////////////////////////////////////////////////////
355 /////////////////////////////////////////////////////////////////////
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))
362 connect(&status_timer_, SIGNAL(timeout()),
363 this, SLOT(doStatusMessage()));
364 status_timer_.start(1000);
368 void Compare::doStatusMessage()
370 statusMessage(pimpl_->status());
376 if (!dest_buffer || !new_buffer || !old_buffer)
379 // Copy the buffer params to the destination buffer
380 dest_buffer->params() = options_.settings_from_new
381 ? new_buffer->params() : old_buffer->params();
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);
396 finished(pimpl_->abort_);
401 int Compare::doCompare()
403 return pimpl_->diff(new_buffer, old_buffer, dest_buffer);
407 void Compare::abort()
409 pimpl_->abort_ = true;
410 condition_.wakeOne();
412 pimpl_->abort_ = false;
416 static void getParagraphList(DocRange const & range,
417 ParagraphList & pars)
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));
426 // Remove the end of the last paragraph; afterwards, remove the
427 // beginning of the first paragraph. Keep this order - there may only
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);
434 pars.insert(pars.begin(), tmp_pars.begin(), tmp_pars.end());
438 static bool equal(Inset const * i_o, Inset const * i_n)
443 // Different types of insets
444 if (i_o->lyxCode() != i_n->lyxCode())
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())
462 return o_os.str() == n_os.str();
466 static bool equal(DocIterator & o, DocIterator & n)
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;
475 Paragraph const & old_par = o.text()->getPar(o.pit());
476 Paragraph const & new_par = n.text()->getPar(n.pit());
478 char_type const c_o = old_par.getChar(o.pos());
479 char_type const c_n = new_par.getChar(n.pos());
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());
488 return equal(i_o, i_n);
491 Font fo = old_par.getFontSettings(o.buffer()->params(), o.pos());
492 Font fn = new_par.getFontSettings(n.buffer()->params(), n.pos());
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
501 static bool traverseSnake(DocPair & p, DocRangePair const & range,
505 DocPair const & p_end =
506 direction == Forward ? range.to() : range.from();
509 if (direction == Backward)
511 if (!equal(p.o, p.n)) {
512 if (direction == Backward)
516 if (direction == Forward)
524 /////////////////////////////////////////////////////////////////////
528 /////////////////////////////////////////////////////////////////////
531 void Compare::Impl::furthestDpathKdiagonal(int D, int k,
532 DocRangePair const & rp, Direction direction)
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;
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];
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]);
551 // If D==0 we simulate a vertical step from (0,-1) by doing nothing.
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);
565 if (traverseSnake(p, rp, direction)) {
570 // Copy last snake from the previous step
575 //Record new position
581 bool Compare::Impl::overlap(int k, int D)
583 // To generalize for the forward and reverse checks
584 int kk = offset_reverse_diagonal_ - k;
586 // Can we have overlap ?
587 if (kk <= D && kk >= -D) {
588 // Do we have overlap ?
590 return ofp[k] >= orp[kk] && nfp[k] >= nrp[kk];
592 return ofp[kk] >= orp[k] && nfp[kk] >= nrp[k];
598 Compare::Impl::SnakeResult Compare::Impl::retrieveMiddleSnake(
599 int k, int D, Direction direction, DocPair & middle_snake)
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;
606 // The diagonal while doing the backward search
607 int kk = -k + offset_reverse_diagonal_;
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_);
618 // Yes, but there is only 1 snake and we found it in the
620 middle_snake.o = os_r[kk];
621 middle_snake.n = ns_r[kk];
625 middle_snake.o = os[k];
626 middle_snake.n = ns[k];
631 int Compare::Impl::findMiddleSnake(DocRangePair const & rp,
632 DocPair & middle_snake)
634 // The lengths of the old and new chunks.
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_;
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);
646 ofp.reset(rp.o.from);
647 nfp.reset(rp.n.from);
648 ofs.reset(DocIterator());
649 nfs.reset(DocIterator());
652 ors.reset(DocIterator());
653 nrs.reset(DocIterator());
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
663 // Forward and reverse paths
664 for (int f = 0; f < 2; ++f) {
665 Direction direction = f == 0 ? Forward : Backward;
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);
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)) {
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_;
687 // This should never be reached
692 bool Compare::Impl::diff(Buffer const * new_buf, Buffer const * old_buf,
693 Buffer const * dest_buf)
695 if (!new_buf || !old_buf || !dest_buf)
700 dest_buf_ = dest_buf;
701 dest_pars_ = &dest_buf->inset().asInsetText()->paragraphs();
704 recursion_level_ = 0;
705 nested_inset_level_ = 0;
707 DocRangePair rp(old_buf_, new_buf_);
709 DocPair from = rp.from();
710 traverseSnake(from, rp, Forward);
711 DocRangePair const snake(rp.from(), from);
714 // Start the recursive algorithm
715 DocRangePair rp_new(from, rp.to());
716 if (!rp_new.o.empty() || !rp_new.n.empty())
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());
728 void Compare::Impl::diff_i(DocRangePair const & rp)
734 DocPair middle_snake;
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);
740 // Set maximum of progress bar
741 if (++recursion_level_ == 1)
742 compare_.progressMax(L_ses);
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.
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);
752 else if (middle_snake.o.empty()) {
753 // Two totally different strings
754 writeToDestBuffer(rp.o, Change::DELETED);
755 writeToDestBuffer(rp.n, Change::INSERTED);
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);
763 DocPair second_part_begin = middle_snake;
764 traverseSnake(second_part_begin, rp, Forward);
765 DocRangePair second_part(second_part_begin, rp.to());
767 // Split the string in three parts:
768 // 1. in front of the snake
769 diffPart(first_part);
771 // 2. the snake itself, and
772 DocRangePair const snake(first_part.to(), second_part.from());
775 // 3. behind the snake.
776 diffPart(second_part);
782 void Compare::Impl::diffPart(DocRangePair const & rp)
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())
789 else if (!rp.o.empty())
790 writeToDestBuffer(rp.o, Change::DELETED);
792 else if (!rp.n.empty())
793 writeToDestBuffer(rp.n, Change::INSERTED);
797 void Compare::Impl::diffInset(Inset * inset, DocPair const & p)
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);
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();
809 ++nested_inset_level_;
811 --nested_inset_level_;
813 dest_pars_ = backup_dest_pars;
817 void Compare::Impl::processSnake(DocRangePair const & rp)
820 getParagraphList(rp.o, pars);
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);
837 writeToDestBuffer(pars);
841 void Compare::Impl::writeToDestBuffer(DocRange const & range,
845 getParagraphList(range, pars);
850 ParagraphList::iterator it = pars.begin();
851 for (; it != pars.end(); ++it) {
852 it->setChange(Change(type));
856 writeToDestBuffer(pars);
858 if (nested_inset_level_ == 0)
859 compare_.progress(size);
863 void Compare::Impl::writeToDestBuffer(ParagraphList const & pars) const
865 pit_type const pit = dest_pars_->size() - 1;
866 dest_pars_->insert(dest_pars_->end(), pars.begin(), pars.end());
868 mergeParagraph(dest_buf_->params(), *dest_pars_, pit);
872 #include "moc_Compare.cpp"