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"
18 #include "insets/InsetText.h"
20 #include "support/lassert.h"
21 #include "support/qstring_helpers.h"
23 #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();
103 DocPair(DocIterator o_, DocIterator n_)
107 bool operator!=(DocPair const & rhs) {
108 // this might not be intuitive but correct for our purpose
109 return o != rhs.o && n != rhs.n;
113 DocPair & operator++()
120 DocPair & operator--()
133 * A pair of two DocRanges.
137 DocRangePair(DocRange o_, DocRange n_)
141 DocRangePair(DocPair from, DocPair to)
142 : o(from.o, to.o), n(from.n, to.n)
145 DocRangePair(Buffer const * o_buf, Buffer const * n_buf)
149 /// Returns the from pair
150 DocPair from() const { return DocPair(o.from, n.from); }
152 /// Returns the to pair
153 DocPair to() const { return DocPair(o.to, n.to); }
160 static DocRangePair stepIntoInset(DocPair const & inset_location)
162 DocRangePair rp(inset_location, inset_location);
163 rp.o.from.forwardPos();
164 rp.n.from.forwardPos();
165 step(rp.o.to, Forward);
166 step(rp.n.to, Forward);
167 rp.o.to.backwardPos();
168 rp.n.to.backwardPos();
174 * This class is designed to hold a vector that has both positive as
175 * negative indices. It is internally represented as two vectors, one
176 * for non-zero indices and one for negative indices. In this way, the
177 * vector can grow in both directions.
178 * If an index is not available in the vector, the default value is
179 * returned. If an object is put in the vector beyond its size, the
180 * empty spots in between are also filled with the default value.
187 void reset(T const & def)
194 /// Gets the value at index. If it is not in the vector
195 /// the default value is inserted and returned.
196 T & operator[](int index) {
197 vector<T> & V = index >= 0 ? Vp_ : Vn_;
198 unsigned int const ii = index >= 0 ? index : -index - 1;
199 while (ii >= V.size())
200 V.push_back(default_);
205 /// The vector for positive indices
207 /// The vector for negative indices
209 /// The default value that is inserted in the vector
210 /// if more space is needed
216 * The implementation of the algorithm that does the comparison
217 * between two documents.
219 class Compare::Impl {
222 Impl(Compare const & compare)
223 : abort_(false), compare_(compare), recursion_level_(0), D_(0)
229 // Algorithm to find the shortest edit string. This algorithm
230 // only needs a linear amount of memory (linear with the sum
231 // of the number of characters in the two paragraph-lists).
232 bool diff(Buffer const * new_buf, Buffer const * old_buf,
233 Buffer const * dest_buf);
235 /// Set to true to cancel the algorithm
241 status += toqstr("recursion level:") + " " + QString::number(recursion_level_)
242 + " " + toqstr("differences:") + " " + QString::number(D_);
247 /// Finds the middle snake and returns the length of the
248 /// shortest edit script.
249 int findMiddleSnake(DocRangePair const & rp, DocPair & middle_snake);
257 /// Retrieve the middle snake when there is overlap between
258 /// the forward and backward path.
259 SnakeResult retrieveMiddleSnake(int k, int D, Direction direction,
260 DocPair & middle_snake);
262 /// Find the the furthest reaching D-path (number of horizontal
263 /// and vertical steps; differences between the old and new
264 /// document) in the k-diagonal (vertical minus horizontal steps).
265 void furthestDpathKdiagonal(int D, int k,
266 DocRangePair const & rp, Direction direction);
268 /// Is there overlap between the forward and backward path
269 bool overlap(int k, int D);
271 /// This function is called recursively by a divide and conquer
272 /// algorithm. Each time, the string is divided into two split
273 /// around the middle snake.
274 void diff_i(DocRangePair const & rp);
276 /// Processes the splitted chunks. It either adds them as deleted,
277 /// as added, or call diff_i for further processing.
278 void diffPart(DocRangePair const & rp);
280 /// Runs the algorithm for the inset located at /c it and /c it_n
281 /// and adds the result to /c pars.
282 void diffInset(Inset * inset, DocPair const & p);
284 /// Adds the snake to the destination buffer. The algorithm will
285 /// recursively be applied to any InsetTexts that are within the snake.
286 void processSnake(DocRangePair const & rp);
288 /// Writes the range to the destination buffer
289 void writeToDestBuffer(DocRange const & range,
290 Change::Type type = Change::UNCHANGED);
292 /// Writes the paragraph list to the destination buffer
293 void writeToDestBuffer(ParagraphList const & copy_pars) const;
295 /// The length of the old chunk currently processed
297 /// The length of the new chunk currently processed
299 /// The offset diagonal of the reverse path of the
300 /// currently processed chunk
301 int offset_reverse_diagonal_;
302 /// Is the offset odd or even ?
305 /// The thread object, used to emit signals to the GUI
306 Compare const & compare_;
308 /// The buffer containing text that will be marked as old
309 Buffer const * old_buf_;
310 /// The buffer containing text that will be marked as new
311 Buffer const * new_buf_;
312 /// The buffer containing text that will be marked as new
313 Buffer const * dest_buf_;
315 /// The paragraph list of the destination buffer
316 ParagraphList * dest_pars_;
318 /// The level of recursion
319 int recursion_level_;
321 /// The number of nested insets at this level
322 int nested_inset_level_;
324 /// The position/snake in the old/new document
325 /// of the forward/reverse search
326 compl_vector<DocIterator> ofp;
327 compl_vector<DocIterator> nfp;
328 compl_vector<DocIterator> ofs;
329 compl_vector<DocIterator> nfs;
330 compl_vector<DocIterator> orp;
331 compl_vector<DocIterator> nrp;
332 compl_vector<DocIterator> ors;
333 compl_vector<DocIterator> nrs;
335 /// The number of differences in the path the algorithm
336 /// is currently processing.
340 /////////////////////////////////////////////////////////////////////
344 /////////////////////////////////////////////////////////////////////
346 Compare::Compare(Buffer const * new_buf, Buffer const * old_buf,
347 Buffer * const dest_buf, CompareOptions const & options)
348 : new_buffer(new_buf), old_buffer(old_buf), dest_buffer(dest_buf),
349 options_(options), pimpl_(new Impl(*this))
351 connect(&status_timer_, SIGNAL(timeout()),
352 this, SLOT(doStatusMessage()));
353 status_timer_.start(1000);
357 void Compare::doStatusMessage()
359 statusMessage(pimpl_->status());
365 if (!dest_buffer || !new_buffer || !old_buffer)
368 // Copy the buffer params to the new buffer
369 dest_buffer->params() = options_.settings_from_new
370 ? new_buffer->params() : old_buffer->params();
378 finished(pimpl_->abort_);
383 int Compare::doCompare()
385 return pimpl_->diff(new_buffer, old_buffer, dest_buffer);
389 void Compare::abort()
391 pimpl_->abort_ = true;
392 condition_.wakeOne();
394 pimpl_->abort_ = false;
398 static void getParagraphList(DocRange const & range,
399 ParagraphList & pars)
401 // Clone the paragraphs within the selection.
402 pit_type startpit = range.from.pit();
403 pit_type endpit = range.to.pit();
404 ParagraphList const & ps_ = range.text()->paragraphs();
405 ParagraphList tmp_pars(boost::next(ps_.begin(), startpit),
406 boost::next(ps_.begin(), endpit + 1));
408 // Remove the end of the last paragraph; afterwards, remove the
409 // beginning of the first paragraph. Keep this order - there may only
411 Paragraph & back = tmp_pars.back();
412 back.eraseChars(range.to.pos(), back.size(), false);
413 Paragraph & front = tmp_pars.front();
414 front.eraseChars(0, range.from.pos(), false);
416 pars.insert(pars.begin(), tmp_pars.begin(), tmp_pars.end());
420 static bool equal(Inset const * i_o, Inset const * i_n)
425 // Different types of insets
426 if (i_o->lyxCode() != i_n->lyxCode())
429 // Editable insets are assumed to be the same as they are of the
430 // same type. If we later on decide that we insert them in the
431 // document as being unchanged, we will run the algorithm on the
432 // contents of the two insets.
433 // FIXME: This fails if the parameters of the insets differ.
434 // FIXME: We do not recurse into InsetTabulars.
435 // FIXME: We need methods inset->equivalent(inset).
436 if (i_o->editable() && !i_o->asInsetMath()
437 && i_o->asInsetText())
444 return o_os.str() == n_os.str();
448 static bool equal(DocIterator & o, DocIterator & n) {
449 Paragraph const & old_par = o.text()->getPar(o.pit());
450 Paragraph const & new_par = n.text()->getPar(n.pit());
452 char_type const c_o = old_par.getChar(o.pos());
453 char_type const c_n = new_par.getChar(n.pos());
457 if (old_par.isInset(o.pos())) {
458 Inset const * i_o = old_par.getInset(o.pos());
459 Inset const * i_n = new_par.getInset(n.pos());
462 return equal(i_o, i_n);
465 Font fo = old_par.getFontSettings(o.buffer()->params(), o.pos());
466 Font fn = new_par.getFontSettings(n.buffer()->params(), n.pos());
471 /// Traverses a snake in a certain direction. p points to a
472 /// position in the old and new file and they are synchronously
473 /// moved along the snake. The function returns true if a snake
475 static bool traverseSnake(DocPair & p, DocRangePair const & range,
479 DocPair const & p_end =
480 direction == Forward ? range.to() : range.from();
483 if (direction == Backward)
485 if (!equal(p.o, p.n)) {
486 if (direction == Backward)
490 if (direction == Forward)
498 /////////////////////////////////////////////////////////////////////
502 /////////////////////////////////////////////////////////////////////
505 void Compare::Impl::furthestDpathKdiagonal(int D, int k,
506 DocRangePair const & rp, Direction direction)
508 compl_vector<DocIterator> & op = direction == Forward ? ofp : orp;
509 compl_vector<DocIterator> & np = direction == Forward ? nfp : nrp;
510 compl_vector<DocIterator> & os = direction == Forward ? ofs : ors;
511 compl_vector<DocIterator> & ns = direction == Forward ? nfs : nrs;
513 // A vertical step means stepping one character in the new document.
514 bool vertical_step = k == -D;
515 if (!vertical_step && k != D) {
516 vertical_step = direction == Forward
517 ? op[k - 1] < op[k + 1] : op[k - 1] > op[k + 1];
520 // Where do we take the step from ?
521 int const kk = vertical_step ? k + 1 : k - 1;
522 DocPair p(op[kk], np[kk]);
524 // If D==0 we simulate a vertical step from (0,-1) by doing nothing.
527 if (vertical_step && direction == Forward)
528 step(p.n, rp.n.to, direction);
529 else if (vertical_step && direction == Backward)
530 step(p.n, rp.n.from, direction);
531 else if (!vertical_step && direction == Forward)
532 step(p.o, rp.o.to, direction);
533 else if (!vertical_step && direction == Backward)
534 step(p.o, rp.o.from, direction);
538 if (traverseSnake(p, rp, direction)) {
543 // Copy last snake from the previous step
548 //Record new position
554 bool Compare::Impl::overlap(int k, int D)
556 // To generalize for the forward and reverse checks
557 int kk = offset_reverse_diagonal_ - k;
559 // Can we have overlap ?
560 if (kk <= D && kk >= -D) {
561 // Do we have overlap ?
563 return ofp[k] >= orp[kk] && nfp[k] >= nrp[kk];
565 return ofp[kk] >= orp[k] && nfp[kk] >= nrp[k];
571 Compare::Impl::SnakeResult Compare::Impl::retrieveMiddleSnake(
572 int k, int D, Direction direction, DocPair & middle_snake)
574 compl_vector<DocIterator> & os = direction == Forward ? ofs : ors;
575 compl_vector<DocIterator> & ns = direction == Forward ? nfs : nrs;
576 compl_vector<DocIterator> & os_r = direction == Forward ? ors : ofs;
577 compl_vector<DocIterator> & ns_r = direction == Forward ? nrs : nfs;
579 // The diagonal while doing the backward search
580 int kk = -k + offset_reverse_diagonal_;
582 // Did we find a snake ?
583 if (os[k].empty() && os_r[kk].empty()) {
584 // No, there is no snake at all, in which case
585 // the length of the shortest edit script is M+N.
586 LASSERT(2 * D - odd_offset_ == M_ + N_, /**/);
591 // Yes, but there is only 1 snake and we found it in the
593 middle_snake.o = os_r[kk];
594 middle_snake.n = ns_r[kk];
598 middle_snake.o = os[k];
599 middle_snake.n = ns[k];
604 int Compare::Impl::findMiddleSnake(DocRangePair const & rp,
605 DocPair & middle_snake)
607 // The lengths of the old and new chunks.
611 // Forward paths are centered around the 0-diagonal; reverse paths
612 // are centered around the diagonal N - M. (Delta in the article)
613 offset_reverse_diagonal_ = N_ - M_;
615 // If the offset is odd, only check for overlap while extending forward
616 // paths, otherwise only check while extending reverse paths.
617 odd_offset_ = (offset_reverse_diagonal_ % 2 != 0);
619 ofp.reset(rp.o.from);
620 nfp.reset(rp.n.from);
621 ofs.reset(DocIterator());
622 nfs.reset(DocIterator());
625 ors.reset(DocIterator());
626 nrs.reset(DocIterator());
628 // D is the number of horizontal and vertical steps, i.e.
629 // different characters in the old and new chunk.
630 int const D_max = ceil(((double)M_ + N_)/2);
631 for (int D = 0; D <= D_max; ++D) {
632 // to be used in the status messages
635 // Forward and reverse paths
636 for (int f = 0; f < 2; ++f) {
637 Direction direction = f == 0 ? Forward : Backward;
639 // Diagonals between -D and D can be reached by a D-path
640 for (int k = -D; k <= D; k += 2) {
641 // Find the furthest reaching D-path on this diagonal
642 furthestDpathKdiagonal(D, k, rp, direction);
644 // Only check for overlap for forward paths if the offset is odd
645 // and only for reverse paths if the offset is even.
646 if (odd_offset_ == (direction == Forward)) {
648 // Do the forward and backward paths overlap ?
649 if (overlap(k, D - odd_offset_)) {
650 retrieveMiddleSnake(k, D, direction, middle_snake);
651 return 2 * D - odd_offset_;
659 // This should never be reached
664 bool Compare::Impl::diff(Buffer const * new_buf, Buffer const * old_buf,
665 Buffer const * dest_buf)
667 if (!new_buf || !old_buf || !dest_buf)
672 dest_buf_ = dest_buf;
673 dest_pars_ = &dest_buf->inset().asInsetText()->paragraphs();
676 recursion_level_ = 0;
677 nested_inset_level_ = 0;
679 DocRangePair rp(old_buf_, new_buf_);
681 DocPair from = rp.from();
682 traverseSnake(from, rp, Forward);
683 DocRangePair const snake(rp.from(), from);
686 // Start the recursive algorithm
689 for (pit_type p = 0; p < (pit_type)dest_pars_->size(); ++p) {
690 (*dest_pars_)[p].setBuffer(const_cast<Buffer &>(*dest_buf));
691 (*dest_pars_)[p].setInsetOwner(&dest_buf_->inset());
698 void Compare::Impl::diff_i(DocRangePair const & rp)
704 DocPair middle_snake;
706 // Divides the problem into two smaller problems, split around
707 // the snake in the middle.
708 int const L_ses = findMiddleSnake(rp, middle_snake);
710 // Set maximum of progress bar
711 if (++recursion_level_ == 1)
712 compare_.progressMax(L_ses);
714 // There are now three possibilities: the strings were the same,
715 // the strings were completely different, or we found a middle
716 // snake and we can split the string into two parts to process.
718 // Two the same strings (this must be a very rare case, because
719 // usually this will be part of a snake adjacent to these strings).
720 writeToDestBuffer(rp.o);
722 else if (middle_snake.o.empty()) {
723 // Two totally different strings
724 writeToDestBuffer(rp.o, Change::DELETED);
725 writeToDestBuffer(rp.n, Change::INSERTED);
728 // Retrieve the complete snake
729 DocPair first_part_end = middle_snake;
730 traverseSnake(first_part_end, rp, Backward);
731 DocRangePair first_part(rp.from(), first_part_end);
733 DocPair second_part_begin = middle_snake;
734 traverseSnake(second_part_begin, rp, Forward);
735 DocRangePair second_part(second_part_begin, rp.to());
737 // Split the string in three parts:
738 // 1. in front of the snake
739 diffPart(first_part);
741 // 2. the snake itself, and
742 DocRangePair const snake(first_part.to(), second_part.from());
745 // 3. behind the snake.
746 diffPart(second_part);
752 void Compare::Impl::diffPart(DocRangePair const & rp)
754 // Is there a finite length string in both buffers, if not there
755 // is an empty string and we write the other one to the buffer.
756 if (!rp.o.empty() && !rp.n.empty())
759 else if (!rp.o.empty())
760 writeToDestBuffer(rp.o, Change::DELETED);
762 else if (!rp.n.empty())
763 writeToDestBuffer(rp.n, Change::INSERTED);
767 void Compare::Impl::diffInset(Inset * inset, DocPair const & p)
769 // Find the dociterators for the beginning and the
770 // end of the inset, for the old and new document.
771 DocRangePair const rp = stepIntoInset(p);
773 // Recurse into the inset. Temporarily replace the dest_pars
774 // paragraph list by the paragraph list of the nested inset.
775 ParagraphList * backup_dest_pars = dest_pars_;
776 dest_pars_ = &inset->asInsetText()->text().paragraphs();
779 ++nested_inset_level_;
781 --nested_inset_level_;
783 dest_pars_ = backup_dest_pars;
787 void Compare::Impl::processSnake(DocRangePair const & rp)
790 getParagraphList(rp.o, pars);
792 // Find insets in this paragaph list
793 DocPair it = rp.from();
794 for (; it.o < rp.o.to; ++it) {
795 Inset * inset = it.o.text()->getPar(it.o.pit()).getInset(it.o.pos());
796 if (inset && inset->editable() && inset->asInsetText()) {
797 // Find the inset in the paragraph list that will be pasted into
798 // the final document. The contents of the inset will be replaced
799 // by the output of the algorithm below.
800 pit_type const pit = it.o.pit() - rp.o.from.pit();
801 pos_type const pos = pit ? it.o.pos() : it.o.pos() - rp.o.from.pos();
802 inset = pars[pit].getInset(pos);
803 LASSERT(inset, /**/);
804 diffInset(inset, it);
807 writeToDestBuffer(pars);
811 void Compare::Impl::writeToDestBuffer(DocRange const & range,
815 getParagraphList(range, pars);
820 ParagraphList::iterator it = pars.begin();
821 for (; it != pars.end(); ++it) {
822 it->setChange(Change(type));
826 writeToDestBuffer(pars);
828 if (nested_inset_level_ == 0)
829 compare_.progress(size);
833 void Compare::Impl::writeToDestBuffer(ParagraphList const & pars) const
835 pit_type const pit = dest_pars_->size() - 1;
836 dest_pars_->insert(dest_pars_->end(), pars.begin(), pars.end());
838 mergeParagraph(dest_buf_->params(), *dest_pars_, pit);
842 #include "moc_Compare.cpp"