2 * \file DocIterator.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Alfredo Braunstein
9 * Full author contact details are available in file CREDITS.
15 #include "DocIterator.h"
18 #include "BufferParams.h"
21 #include "InsetList.h"
23 #include "Paragraph.h"
26 #include "mathed/MathData.h"
27 #include "mathed/InsetMath.h"
28 #include "mathed/InsetMathHull.h"
30 #include "insets/InsetTabular.h"
32 #include "support/convert.h"
33 #include "support/debug.h"
34 #include "support/ExceptionMessage.h"
35 #include "support/gettext.h"
36 #include "support/lassert.h"
37 #include "support/lstrings.h"
42 using namespace lyx::support;
47 DocIterator::DocIterator()
48 : boundary_(false), inset_(nullptr), buffer_(nullptr)
52 // We could be able to get rid of this if only every BufferView were
53 // associated to a buffer on construction.
54 DocIterator::DocIterator(Buffer * buf)
55 : boundary_(false), inset_(nullptr), buffer_(buf)
59 DocIterator::DocIterator(Buffer * buf, Inset * inset)
60 : boundary_(false), inset_(inset), buffer_(buf)
64 DocIterator doc_iterator_begin(const Buffer * buf0, const Inset * inset0)
66 Buffer * buf = const_cast<Buffer *>(buf0);
67 Inset * inset = const_cast<Inset *>(inset0);
68 DocIterator dit(buf, inset ? inset : &buf->inset());
74 DocIterator doc_iterator_end(const Buffer * buf0, const Inset * inset0)
76 Buffer * buf = const_cast<Buffer *>(buf0);
77 Inset * inset = const_cast<Inset *>(inset0);
78 return DocIterator(buf, inset ? inset : &buf->inset());
82 DocIterator DocIterator::clone(Buffer * buffer) const
84 LASSERT(buffer->isClone(), return DocIterator());
85 Inset * inset = &buffer->inset();
86 DocIterator dit(buffer);
87 size_t const n = slices_.size();
88 for (size_t i = 0 ; i != n; ++i) {
90 dit.push_back(slices_[i]);
91 dit.top().inset_ = inset;
93 inset = dit.nextInset();
99 bool DocIterator::inRegexped() const
101 InsetMath * im = inset().asInsetMath();
104 InsetMathHull * hull = im->asHullInset();
105 return hull && hull->getType() == hullRegexp;
109 LyXErr & operator<<(LyXErr & os, DocIterator const & it)
116 Inset * DocIterator::nextInset() const
118 LASSERT(!empty(), return nullptr);
119 if (pos() == lastpos())
121 if (pos() > lastpos()) {
122 LYXERR0("Should not happen, but it does: pos() = "
123 << pos() << ", lastpos() = " << lastpos());
127 return nextAtom().nucleus();
128 return paragraph().getInset(pos());
132 Inset * DocIterator::prevInset() const
134 LASSERT(!empty(), return nullptr);
139 // FIXME: this should not happen but it does.
141 // http://www.lyx.org/trac/ticket/3189
144 return prevAtom().nucleus();
146 return paragraph().getInset(pos() - 1);
150 Inset * DocIterator::realInset() const
152 LASSERT(inTexted(), return nullptr);
153 // if we are in a tabular, we need the cell
154 if (inset().lyxCode() == TABULAR_CODE) {
155 InsetTabular * tabular = inset().asInsetTabular();
156 return tabular->cell(idx()).get();
162 InsetMath & DocIterator::nextMath()
164 return *nextAtom().nucleus();
168 InsetMath & DocIterator::prevMath()
170 return *prevAtom().nucleus();
174 MathAtom & DocIterator::prevAtom() const
176 LASSERT(!empty(), /**/);
177 LASSERT(pos() > 0, /**/);
178 return cell()[pos() - 1];
182 MathAtom & DocIterator::nextAtom() const
184 LASSERT(!empty(), /**/);
185 //lyxerr << "lastpos: " << lastpos() << " next atom:\n" << *this << endl;
186 LASSERT(pos() < lastpos(), /**/);
187 return cell()[pos()];
191 Text * DocIterator::text() const
193 LASSERT(!empty(), return nullptr);
198 Paragraph & DocIterator::paragraph() const
204 return top().paragraph();
208 Paragraph & DocIterator::innerParagraph() const
211 return innerTextSlice().paragraph();
215 FontSpan DocIterator::locateWord(word_location const loc) const
217 FontSpan f = FontSpan();
219 if (!top().text()->empty()) {
221 top().paragraph().locateWord(f.first, f.last, loc);
227 CursorSlice const & DocIterator::innerTextSlice() const
230 // go up until first non-0 text is hit
231 // (innermost text is 0 in mathed)
232 for (int i = depth() - 1; i >= 0; --i)
233 if (slices_[i].text())
236 // This case is in principle not possible. We _must_
240 static const CursorSlice c;
245 docstring DocIterator::paragraphGotoArgument() const
247 CursorSlice const & s = innerTextSlice();
248 return convert<docstring>(s.paragraph().id()) + ' ' +
249 convert<docstring>(s.pos());
253 DocIterator DocIterator::getInnerText() const
255 DocIterator texted = *this;
256 while (!texted.inTexted())
262 pit_type DocIterator::lastpit() const
264 return inMathed() ? 0 : text()->paragraphs().size() - 1;
268 pos_type DocIterator::lastpos() const
270 return inMathed() ? cell().size() : paragraph().size();
274 DocIterator::idx_type DocIterator::lastidx() const
276 return top().lastidx();
280 size_t DocIterator::nargs() const
282 // assume 1x1 grid for main text
283 return top().nargs();
287 size_t DocIterator::ncols() const
289 // assume 1x1 grid for main text
290 return top().ncols();
294 size_t DocIterator::nrows() const
296 // assume 1x1 grid for main text
297 return top().nrows();
301 DocIterator::row_type DocIterator::row() const
307 DocIterator::col_type DocIterator::col() const
313 MathData & DocIterator::cell() const
315 // LASSERT(inMathed(), /**/);
320 Text * DocIterator::innerText() const
322 LASSERT(!empty(), return nullptr);
323 return innerTextSlice().text();
327 Inset * DocIterator::innerInsetOfType(int code) const
329 for (int i = depth() - 1; i >= 0; --i)
330 if (slices_[i].inset_->lyxCode() == code)
331 return slices_[i].inset_;
336 bool DocIterator::posBackward()
345 bool DocIterator::posForward()
347 if (pos() == lastpos())
354 // This duplicates code above, but is in the critical path.
355 // So please think twice before adding stuff
356 void DocIterator::forwardPos()
358 // this dog bites his tail
360 push_back(CursorSlice(*inset_));
364 CursorSlice & tip = top();
365 //lyxerr << "XXX\n" << *this << endl;
367 // not at cell/paragraph end?
368 if (tip.pos() != tip.lastpos()) {
369 // move into an inset to the right if possible
372 n = (tip.cell().begin() + tip.pos())->nucleus();
374 n = paragraph().getInset(tip.pos());
375 if (n && n->isActive()) {
376 //lyxerr << "... descend" << endl;
377 push_back(CursorSlice(*n));
382 // jump to the next cell/paragraph if possible
388 // otherwise leave inset and jump over inset as a whole
390 // 'tip' is invalid now...
396 void DocIterator::forwardPosIgnoreCollapsed()
398 Inset * const nextinset = nextInset();
399 // FIXME: the check for asInsetMath() shouldn't be necessary
400 // but math insets do not return a sensible editable() state yet.
401 if (nextinset && !nextinset->asInsetMath()
402 && !nextinset->editable()) {
410 void DocIterator::forwardPar()
414 while (!empty() && (!inTexted() || pos() != 0)) {
416 pos_type const lastp = lastpos();
417 Paragraph const & par = paragraph();
418 pos_type & pos = top().pos();
419 if (par.insetList().empty())
422 while (pos < lastp && !par.isInset(pos))
430 void DocIterator::forwardChar()
433 while (!empty() && pos() == lastpos())
438 void DocIterator::forwardInset()
442 while (!empty() && !nextInset()) {
444 pos_type const lastp = lastpos();
445 Paragraph const & par = paragraph();
446 pos_type & pos = top().pos();
447 while (pos < lastp && !par.isInset(pos))
457 void DocIterator::backwardChar()
460 while (!empty() && pos() == lastpos())
465 void DocIterator::backwardPos()
467 //this dog bites his tail
469 push_back(CursorSlice(*inset_));
470 top().idx() = lastidx();
471 top().pit() = lastpit();
472 top().pos() = lastpos();
476 // at inset beginning?
477 if (top().at_begin()) {
484 // entered another cell/paragraph from the right?
485 if (top().pos() == top().lastpos())
488 // move into an inset to the left if possible
491 n = (top().cell().begin() + top().pos())->nucleus();
493 n = paragraph().getInset(top().pos());
494 if (n && n->isActive()) {
495 push_back(CursorSlice(*n));
496 top().idx() = lastidx();
497 top().pit() = lastpit();
498 top().pos() = lastpos();
503 void DocIterator::backwardPosIgnoreCollapsed()
507 Inset const * ins = realInset();
508 if (ins && !ins->editable()) {
509 pop_back(); // move out of collapsed inset
516 // works, but currently not needed
517 void DocIterator::backwardInset()
521 while (!empty() && !nextInset()) {
523 pos_type const lastp = lastpos();
524 Paragraph const & par = paragraph();
525 pos_type & pos = top().pos();
526 while (pos > 0 && (pos == lastp || !par.isInset(pos)))
537 bool DocIterator::hasPart(DocIterator const & it) const
539 // it can't be a part if it is larger
540 if (it.depth() > depth())
543 // as inset adresses are the 'last' level
544 return &it.top().inset() == &slices_[it.depth() - 1].inset();
548 bool DocIterator::allowSpellCheck() const
550 /// spell check is disabled if the iterator position
551 /// is inside of an inset which disables the spell checker
552 size_t const n = depth();
553 for (size_t i = 0; i < n; ++i) {
554 if (!slices_[i].inset_->allowSpellCheck())
561 void DocIterator::updateInsets(Inset * inset)
563 // this function re-creates the cache of inset pointers.
564 //lyxerr << "converting:\n" << *this << endl;
565 DocIterator dit = *this;
566 size_t const n = slices_.size();
568 for (size_t i = 0 ; i < n; ++i) {
571 top().inset_ = inset;
575 //lyxerr << "converted:\n" << *this << endl;
579 bool DocIterator::fixIfBroken()
584 // Go through the slice stack from the bottom.
585 // Check that all coordinates (idx, pit, pos) are correct and
586 // that the inset is the one which is claimed to be there
587 Inset * inset = &slices_[0].inset();
589 size_t n = slices_.size();
590 for (; i != n; ++i) {
591 CursorSlice & cs = slices_[i];
592 if (&cs.inset() != inset || ! cs.inset().isActive()) {
593 // the whole slice is wrong, chop off this as well
595 LYXERR(Debug::DEBUG, "fixIfBroken(): inset changed");
597 } else if (cs.idx() > cs.lastidx()) {
598 cs.idx() = cs.lastidx();
599 cs.pit() = cs.lastpit();
600 cs.pos() = cs.lastpos();
601 LYXERR(Debug::DEBUG, "fixIfBroken(): idx fixed");
603 } else if (cs.pit() > cs.lastpit()) {
604 cs.pit() = cs.lastpit();
605 cs.pos() = cs.lastpos();
606 LYXERR(Debug::DEBUG, "fixIfBroken(): pit fixed");
608 } else if (cs.pos() > cs.lastpos()) {
609 cs.pos() = cs.lastpos();
610 LYXERR(Debug::DEBUG, "fixIfBroken(): pos fixed");
612 } else if (i != n - 1 && cs.pos() != cs.lastpos()) {
613 // get inset which is supposed to be in the next slice
614 if (cs.inset().inMathed())
615 inset = (cs.cell().begin() + cs.pos())->nucleus();
616 else if (Inset * csInset = cs.paragraph().getInset(cs.pos()))
619 // there are slices left, so there must be another inset
625 // Did we make it through the whole slice stack? Otherwise there
626 // was a problem at slice i, and we have to chop off above
628 LYXERR(Debug::DEBUG, "fixIfBroken(): cursor chopped at " << i);
636 void DocIterator::sanitize()
638 // keep a copy of the slices
639 vector<CursorSlice> const sl = slices_;
642 inset_ = &buffer_->inset();
643 Inset * inset = inset_;
644 // re-add the slices one by one, and adjust the inset pointer.
645 for (size_t i = 0, n = sl.size(); i != n; ++i) {
646 if (inset == nullptr) {
648 LYXERR0("Null inset on cursor stack.");
652 if (!inset->isActive()) {
653 LYXERR0("Inset found on cursor stack is not active.");
658 top().inset_ = inset;
667 bool DocIterator::isInside(Inset const * p) const
669 for (CursorSlice const & sl : slices_)
670 if (&sl.inset() == p)
676 void DocIterator::leaveInset(Inset const & inset)
678 for (size_t i = 0; i != slices_.size(); ++i) {
679 if (&slices_[i].inset() == &inset) {
687 int DocIterator::find(MathData const & cell) const
689 for (size_t l = 0; l != slices_.size(); ++l) {
690 if (slices_[l].asInsetMath() && &slices_[l].cell() == &cell)
697 int DocIterator::find(Inset const * inset) const
699 for (size_t l = 0; l != slices_.size(); ++l) {
700 if (&slices_[l].inset() == inset)
707 void DocIterator::cutOff(int above, vector<CursorSlice> & cut)
709 cut = vector<CursorSlice>(slices_.begin() + above + 1, slices_.end());
710 slices_.resize(above + 1);
714 void DocIterator::cutOff(int above)
716 slices_.resize(above + 1);
720 void DocIterator::append(vector<CursorSlice> const & x)
722 slices_.insert(slices_.end(), x.begin(), x.end());
726 void DocIterator::append(DocIterator::idx_type idx, pos_type pos)
728 slices_.push_back(CursorSlice());
734 docstring DocIterator::getPossibleLabel() const
736 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
740 Encoding const * DocIterator::getEncoding() const
745 BufferParams const & bp = buffer()->params();
746 if (bp.useNonTeXFonts)
747 return encodings.fromLyXName("utf8-plain");
749 // With platex, we don't switch encodings (not even if forced).
750 if (bp.encoding().package() == Encoding::japanese)
751 return &bp.encoding();
753 CursorSlice const & sl = innerTextSlice();
754 Text const & text = *sl.text();
755 Language const * lang =
756 text.getPar(sl.pit()).getFont(bp, sl.pos(), text.outerFont(sl.pit())).language();
757 // If we have a custom encoding for the buffer, we don't switch
758 // encodings (see output_latex::switchEncoding())
759 bool const customenc = bp.inputenc != "auto-legacy" && bp.inputenc != "auto-legacy-plain";
760 Encoding const * enc = customenc ? &bp.encoding() : lang->encoding();
762 // Some insets force specific encodings sometimes (e.g., listings in
763 // multibyte context forces singlebyte).
764 if (inset().forcedEncoding(enc, encodings.fromLyXName("iso8859-1"))) {
765 // Get the language outside the inset
766 size_t const n = depth();
767 for (size_t i = 0; i < n; ++i) {
768 Text const & otext = *slices_[i].text();
769 Language const * olang =
770 otext.getPar(slices_[i].pit()).getFont(bp, slices_[i].pos(),
771 otext.outerFont(slices_[i].pit())).language();
772 Encoding const * oenc = olang->encoding();
773 if (oenc->name() != "inherit")
774 return inset().forcedEncoding(enc, oenc);
776 // Fall back to buffer encoding if no outer lang was found.
777 return inset().forcedEncoding(enc, &bp.encoding());
780 // Inherited encoding (latex_language) is determined by the context
781 // Look for the first outer encoding that is not itself "inherit"
782 if (lang->encoding()->name() == "inherit") {
783 size_t const n = depth();
784 for (size_t i = 0; i < n; ++i) {
785 Text const & otext = *slices_[i].text();
786 Language const * olang =
787 otext.getPar(slices_[i].pit()).getFont(bp, slices_[i].pos(),
788 otext.outerFont(slices_[i].pit())).language();
789 // Again, if we have a custom encoding, this is used
790 // instead of the language's.
791 Encoding const * oenc = customenc ? &bp.encoding() : olang->encoding();
792 if (olang->encoding()->name() != "inherit")
801 ostream & operator<<(ostream & os, DocIterator const & dit)
803 for (size_t i = 0, n = dit.depth(); i != n; ++i)
804 os << " " << dit[i] << "\n";
809 ///////////////////////////////////////////////////////
811 StableDocIterator::StableDocIterator(DocIterator const & dit) :
812 data_(dit.internalData())
814 for (size_t i = 0, n = data_.size(); i != n; ++i)
815 data_[i].inset_ = nullptr;
819 DocIterator StableDocIterator::asDocIterator(Buffer * buf) const
821 DocIterator dit(buf);
828 ostream & operator<<(ostream & os, StableDocIterator const & dit)
830 for (size_t i = 0, n = dit.data_.size(); i != n; ++i)
831 os << " " << dit.data_[i] << "\n";
836 bool operator==(StableDocIterator const & dit1, StableDocIterator const & dit2)
838 return dit1.data_ == dit2.data_;