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/docstream.h"
23 #include "support/lassert.h"
24 #include "support/lyxalgo.h"
25 #include "support/qstring_helpers.h"
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 const & from_, DocIterator const & to_)
62 : from(from_), to(to_)
65 DocRange(Buffer const * buf) :
66 from(doc_iterator_begin(buf)),
67 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 const & o_, DocRange const & n_)
143 DocRangePair(DocPair const & from, DocPair const & 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), n_(0), m_(0), offset_reverse_diagonal_(0),
233 odd_offset_(0), compare_(compare),
234 old_buf_(0), new_buf_(0), dest_buf_(0), dest_pars_(0),
235 recursion_level_(0), nested_inset_level_(0), D_(0)
242 // Algorithm to find the shortest edit string. This algorithm
243 // only needs a linear amount of memory (linear with the sum
244 // of the number of characters in the two paragraph-lists).
245 bool diff(Buffer const * new_buf, Buffer const * old_buf,
246 Buffer const * dest_buf);
248 /// Set to true to cancel the algorithm
255 status += toqstr("recursion level:") + " " + QString::number(recursion_level_)
256 + " " + toqstr("differences:") + " " + QString::number(D_);
261 /// Finds the middle snake and returns the length of the
262 /// shortest edit script.
263 int findMiddleSnake(DocRangePair const & rp, DocPair & middle_snake);
271 /// Retrieve the middle snake when there is overlap between
272 /// the forward and backward path.
273 SnakeResult retrieveMiddleSnake(int k, int D, Direction direction,
274 DocPair & middle_snake);
276 /// Find the furthest reaching D-path (number of horizontal
277 /// and vertical steps; differences between the old and new
278 /// document) in the k-diagonal (vertical minus horizontal steps).
279 void furthestDpathKdiagonal(int D, int k,
280 DocRangePair const & rp, Direction direction);
282 /// Is there overlap between the forward and backward path
283 bool overlap(int k, int D);
285 /// This function is called recursively by a divide and conquer
286 /// algorithm. Each time, the string is divided into two split
287 /// around the middle snake.
288 void diff_i(DocRangePair const & rp);
290 /// Processes the split chunks. It either adds them as deleted,
291 /// as added, or call diff_i for further processing.
292 void diffPart(DocRangePair const & rp);
294 /// Runs the algorithm for the inset located at /c it and /c it_n
295 /// and adds the result to /c pars.
296 void diffInset(Inset * inset, DocPair const & p);
298 /// Adds the snake to the destination buffer. The algorithm will
299 /// recursively be applied to any InsetTexts that are within the snake.
300 void processSnake(DocRangePair const & rp);
302 /// Writes the range to the destination buffer
303 void writeToDestBuffer(DocRange const & range,
304 Change::Type type = Change::UNCHANGED);
306 /// Writes the paragraph list to the destination buffer
307 void writeToDestBuffer(ParagraphList const & copy_pars) const;
309 /// The length of the old chunk currently processed
311 /// The length of the new chunk currently processed
313 /// The offset diagonal of the reverse path of the
314 /// currently processed chunk
315 int offset_reverse_diagonal_;
316 /// Is the offset odd or even ?
319 /// The thread object, used to emit signals to the GUI
320 Compare const & compare_;
322 /// The buffer containing text that will be marked as old
323 Buffer const * old_buf_;
324 /// The buffer containing text that will be marked as new
325 Buffer const * new_buf_;
326 /// The buffer containing text that will be marked as new
327 Buffer const * dest_buf_;
329 /// The paragraph list of the destination buffer
330 ParagraphList * dest_pars_;
332 /// The level of recursion
333 int recursion_level_;
335 /// The number of nested insets at this level
336 int nested_inset_level_;
338 /// The position/snake in the old/new document
339 /// of the forward/reverse search
340 compl_vector<DocIterator> ofp;
341 compl_vector<DocIterator> nfp;
342 compl_vector<DocIterator> ofs;
343 compl_vector<DocIterator> nfs;
344 compl_vector<DocIterator> orp;
345 compl_vector<DocIterator> nrp;
346 compl_vector<DocIterator> ors;
347 compl_vector<DocIterator> nrs;
349 /// The number of differences in the path the algorithm
350 /// is currently processing.
354 /////////////////////////////////////////////////////////////////////
358 /////////////////////////////////////////////////////////////////////
360 Compare::Compare(Buffer const * new_buf, Buffer const * old_buf,
361 Buffer * const dest_buf, CompareOptions const & options)
362 : new_buffer(new_buf), old_buffer(old_buf), dest_buffer(dest_buf),
363 options_(options), pimpl_(new Impl(*this))
365 connect(&status_timer_, SIGNAL(timeout()),
366 this, SLOT(doStatusMessage()));
367 status_timer_.start(1000);
371 void Compare::doStatusMessage()
373 statusMessage(pimpl_->status());
379 if (!dest_buffer || !new_buffer || !old_buffer)
382 // Copy the buffer params to the destination buffer
383 dest_buffer->params() = options_.settings_from_new
384 ? new_buffer->params() : old_buffer->params();
386 // Copy extra authors to the destination buffer
387 AuthorList const & extra_authors = options_.settings_from_new ?
388 old_buffer->params().authors() : new_buffer->params().authors();
389 AuthorList::Authors::const_iterator it = extra_authors.begin();
390 for (; it != extra_authors.end(); ++it)
391 dest_buffer->params().authors().record(*it);
399 finished(pimpl_->abort_);
404 int Compare::doCompare()
406 return pimpl_->diff(new_buffer, old_buffer, dest_buffer);
410 void Compare::abort()
412 pimpl_->abort_ = true;
413 condition_.wakeOne();
415 pimpl_->abort_ = false;
419 static void getParagraphList(DocRange const & range,
420 ParagraphList & pars)
422 // Clone the paragraphs within the selection.
423 pit_type startpit = range.from.pit();
424 pit_type endpit = range.to.pit();
425 ParagraphList const & ps_ = range.text()->paragraphs();
426 ParagraphList tmp_pars(lyx::next(ps_.begin(), startpit),
427 lyx::next(ps_.begin(), endpit + 1));
429 // Remove the end of the last paragraph; afterwards, remove the
430 // beginning of the first paragraph. Keep this order - there may only
432 Paragraph & back = tmp_pars.back();
433 back.eraseChars(range.to.pos(), back.size(), false);
434 Paragraph & front = tmp_pars.front();
435 front.eraseChars(0, range.from.pos(), false);
437 pars.insert(pars.begin(), tmp_pars.begin(), tmp_pars.end());
441 static bool equal(Inset const * i_o, Inset const * i_n)
446 // Different types of insets
447 if (i_o->lyxCode() != i_n->lyxCode())
450 // Editable insets are assumed to be the same as they are of the
451 // same type. If we later on decide that we insert them in the
452 // document as being unchanged, we will run the algorithm on the
453 // contents of the two insets.
454 // FIXME: This fails if the parameters of the insets differ.
455 // FIXME: We do not recurse into InsetTabulars.
456 // FIXME: We need methods inset->equivalent(inset).
457 if (i_o->editable() && !i_o->asInsetMath()
458 && i_o->asInsetText())
465 return o_os.str() == n_os.str();
469 static bool equal(DocIterator & o, DocIterator & n)
471 // Explicitly check for this, so we won't call
472 // Paragraph::getChar for the last pos.
473 bool const o_lastpos = o.pos() == o.lastpos();
474 bool const n_lastpos = n.pos() == n.lastpos();
475 if (o_lastpos || n_lastpos)
476 return o_lastpos && n_lastpos;
478 Paragraph const & old_par = o.text()->getPar(o.pit());
479 Paragraph const & new_par = n.text()->getPar(n.pit());
481 char_type const c_o = old_par.getChar(o.pos());
482 char_type const c_n = new_par.getChar(n.pos());
486 if (old_par.isInset(o.pos())) {
487 Inset const * i_o = old_par.getInset(o.pos());
488 Inset const * i_n = new_par.getInset(n.pos());
491 return equal(i_o, i_n);
494 Font fo = old_par.getFontSettings(o.buffer()->params(), o.pos());
495 Font fn = new_par.getFontSettings(n.buffer()->params(), n.pos());
500 /// Traverses a snake in a certain direction. p points to a
501 /// position in the old and new file and they are synchronously
502 /// moved along the snake. The function returns true if a snake
504 static bool traverseSnake(DocPair & p, DocRangePair const & range,
508 DocPair const & p_end =
509 direction == Forward ? range.to() : range.from();
512 if (direction == Backward)
514 if (!equal(p.o, p.n)) {
515 if (direction == Backward)
519 if (direction == Forward)
527 /////////////////////////////////////////////////////////////////////
531 /////////////////////////////////////////////////////////////////////
534 void Compare::Impl::furthestDpathKdiagonal(int D, int k,
535 DocRangePair const & rp, Direction direction)
537 compl_vector<DocIterator> & op = direction == Forward ? ofp : orp;
538 compl_vector<DocIterator> & np = direction == Forward ? nfp : nrp;
539 compl_vector<DocIterator> & os = direction == Forward ? ofs : ors;
540 compl_vector<DocIterator> & ns = direction == Forward ? nfs : nrs;
542 // A vertical step means stepping one character in the new document.
543 bool vertical_step = k == -D;
544 if (!vertical_step && k != D) {
545 vertical_step = direction == Forward
546 ? op[k - 1] < op[k + 1] : op[k - 1] > op[k + 1];
549 // Where do we take the step from ?
550 int const kk = vertical_step ? k + 1 : k - 1;
551 DocPair p(op[kk], np[kk]);
552 DocPair const s(os[kk], ns[kk]);
554 // If D==0 we simulate a vertical step from (0,-1) by doing nothing.
557 if (vertical_step && direction == Forward)
558 step(p.n, rp.n.to, direction);
559 else if (vertical_step && direction == Backward)
560 step(p.n, rp.n.from, direction);
561 else if (!vertical_step && direction == Forward)
562 step(p.o, rp.o.to, direction);
563 else if (!vertical_step && direction == Backward)
564 step(p.o, rp.o.from, direction);
568 if (traverseSnake(p, rp, direction)) {
573 // Copy last snake from the previous step
578 //Record new position
584 bool Compare::Impl::overlap(int k, int D)
586 // To generalize for the forward and reverse checks
587 int kk = offset_reverse_diagonal_ - k;
589 // Can we have overlap ?
590 if (kk <= D && kk >= -D) {
591 // Do we have overlap ?
593 return ofp[k] >= orp[kk] && nfp[k] >= nrp[kk];
595 return ofp[kk] >= orp[k] && nfp[kk] >= nrp[k];
601 Compare::Impl::SnakeResult Compare::Impl::retrieveMiddleSnake(
602 int k, int D, Direction direction, DocPair & middle_snake)
604 compl_vector<DocIterator> & os = direction == Forward ? ofs : ors;
605 compl_vector<DocIterator> & ns = direction == Forward ? nfs : nrs;
606 compl_vector<DocIterator> & os_r = direction == Forward ? ors : ofs;
607 compl_vector<DocIterator> & ns_r = direction == Forward ? nrs : nfs;
609 // The diagonal while doing the backward search
610 int kk = -k + offset_reverse_diagonal_;
612 // Did we find a snake ?
613 if (os[k].empty() && os_r[kk].empty()) {
614 // No, there is no snake at all, in which case
615 // the length of the shortest edit script is M+N.
616 LATTEST(2 * D - odd_offset_ == m_ + n_);
621 // Yes, but there is only 1 snake and we found it in the
623 middle_snake.o = os_r[kk];
624 middle_snake.n = ns_r[kk];
628 middle_snake.o = os[k];
629 middle_snake.n = ns[k];
634 int Compare::Impl::findMiddleSnake(DocRangePair const & rp,
635 DocPair & middle_snake)
637 // The lengths of the old and new chunks.
641 // Forward paths are centered around the 0-diagonal; reverse paths
642 // are centered around the diagonal N - M. (Delta in the article)
643 offset_reverse_diagonal_ = n_ - m_;
645 // If the offset is odd, only check for overlap while extending forward
646 // paths, otherwise only check while extending reverse paths.
647 odd_offset_ = (offset_reverse_diagonal_ % 2 != 0);
649 ofp.reset(rp.o.from);
650 nfp.reset(rp.n.from);
651 ofs.reset(DocIterator());
652 nfs.reset(DocIterator());
655 ors.reset(DocIterator());
656 nrs.reset(DocIterator());
658 // In the formula below, the "+ 1" ensures we round like ceil()
659 int const D_max = (m_ + n_ + 1)/2;
660 // D is the number of horizontal and vertical steps, i.e.
661 // different characters in the old and new chunk.
662 for (int D = 0; D <= D_max; ++D) {
663 // to be used in the status messages
666 // Forward and reverse paths
667 for (int f = 0; f < 2; ++f) {
668 Direction direction = f == 0 ? Forward : Backward;
670 // Diagonals between -D and D can be reached by a D-path
671 for (int k = -D; k <= D; k += 2) {
672 // Find the furthest reaching D-path on this diagonal
673 furthestDpathKdiagonal(D, k, rp, direction);
675 // Only check for overlap for forward paths if the offset is odd
676 // and only for reverse paths if the offset is even.
677 if (odd_offset_ == (direction == Forward)) {
679 // Do the forward and backward paths overlap ?
680 if (overlap(k, D - odd_offset_)) {
681 retrieveMiddleSnake(k, D, direction, middle_snake);
682 return 2 * D - odd_offset_;
690 // This should never be reached
695 bool Compare::Impl::diff(Buffer const * new_buf, Buffer const * old_buf,
696 Buffer const * dest_buf)
698 if (!new_buf || !old_buf || !dest_buf)
703 dest_buf_ = dest_buf;
704 dest_pars_ = &dest_buf->inset().asInsetText()->paragraphs();
707 recursion_level_ = 0;
708 nested_inset_level_ = 0;
710 DocRangePair rp(old_buf_, new_buf_);
712 DocPair from = rp.from();
713 traverseSnake(from, rp, Forward);
714 DocRangePair const snake(rp.from(), from);
717 // Start the recursive algorithm
718 DocRangePair rp_new(from, rp.to());
719 if (!rp_new.o.empty() || !rp_new.n.empty())
722 for (pit_type p = 0; p < (pit_type)dest_pars_->size(); ++p) {
723 (*dest_pars_)[p].setBuffer(const_cast<Buffer &>(*dest_buf));
724 (*dest_pars_)[p].setInsetOwner(&dest_buf_->inset());
731 void Compare::Impl::diff_i(DocRangePair const & rp)
737 DocPair middle_snake;
739 // Divides the problem into two smaller problems, split around
740 // the snake in the middle.
741 int const L_ses = findMiddleSnake(rp, middle_snake);
743 // Set maximum of progress bar
744 if (++recursion_level_ == 1)
745 compare_.progressMax(L_ses);
747 // There are now three possibilities: the strings were the same,
748 // the strings were completely different, or we found a middle
749 // snake and we can split the string into two parts to process.
751 // Two the same strings (this must be a very rare case, because
752 // usually this will be part of a snake adjacent to these strings).
753 writeToDestBuffer(rp.o);
755 else if (middle_snake.o.empty()) {
756 // Two totally different strings
757 writeToDestBuffer(rp.o, Change::DELETED);
758 writeToDestBuffer(rp.n, Change::INSERTED);
761 // Retrieve the complete snake
762 DocPair first_part_end = middle_snake;
763 traverseSnake(first_part_end, rp, Backward);
764 DocRangePair first_part(rp.from(), first_part_end);
766 DocPair second_part_begin = middle_snake;
767 traverseSnake(second_part_begin, rp, Forward);
768 DocRangePair second_part(second_part_begin, rp.to());
770 // Split the string in three parts:
771 // 1. in front of the snake
772 diffPart(first_part);
774 // 2. the snake itself, and
775 DocRangePair const snake(first_part.to(), second_part.from());
778 // 3. behind the snake.
779 diffPart(second_part);
785 void Compare::Impl::diffPart(DocRangePair const & rp)
787 // Is there a finite length string in both buffers, if not there
788 // is an empty string and we write the other one to the buffer.
789 if (!rp.o.empty() && !rp.n.empty())
792 else if (!rp.o.empty())
793 writeToDestBuffer(rp.o, Change::DELETED);
795 else if (!rp.n.empty())
796 writeToDestBuffer(rp.n, Change::INSERTED);
800 void Compare::Impl::diffInset(Inset * inset, DocPair const & p)
802 // Find the dociterators for the beginning and the
803 // end of the inset, for the old and new document.
804 DocRangePair const rp = stepIntoInset(p);
806 // Recurse into the inset. Temporarily replace the dest_pars
807 // paragraph list by the paragraph list of the nested inset.
808 ParagraphList * backup_dest_pars = dest_pars_;
809 dest_pars_ = &inset->asInsetText()->text().paragraphs();
812 ++nested_inset_level_;
814 --nested_inset_level_;
816 dest_pars_ = backup_dest_pars;
820 void Compare::Impl::processSnake(DocRangePair const & rp)
823 getParagraphList(rp.o, pars);
825 // Find insets in this paragaph list
826 DocPair it = rp.from();
827 for (; it.o < rp.o.to; ++it) {
828 Inset * inset = it.o.text()->getPar(it.o.pit()).getInset(it.o.pos());
829 if (inset && inset->editable() && inset->asInsetText()) {
830 // Find the inset in the paragraph list that will be pasted into
831 // the final document. The contents of the inset will be replaced
832 // by the output of the algorithm below.
833 pit_type const pit = it.o.pit() - rp.o.from.pit();
834 pos_type const pos = pit ? it.o.pos() : it.o.pos() - rp.o.from.pos();
835 inset = pars[pit].getInset(pos);
836 LASSERT(inset, continue);
837 diffInset(inset, it);
840 writeToDestBuffer(pars);
844 void Compare::Impl::writeToDestBuffer(DocRange const & range,
848 getParagraphList(range, pars);
853 ParagraphList::iterator it = pars.begin();
854 for (; it != pars.end(); ++it) {
855 it->setChange(Change(type));
859 writeToDestBuffer(pars);
861 if (nested_inset_level_ == 0)
862 compare_.progress(size);
866 void Compare::Impl::writeToDestBuffer(ParagraphList const & pars) const
868 pit_type const pit = dest_pars_->size() - 1;
869 dest_pars_->insert(dest_pars_->end(), pars.begin(), pars.end());
871 mergeParagraph(dest_buf_->params(), *dest_pars_, pit);
875 #include "moc_Compare.cpp"