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 doc_iterator_begin(const Buffer * buf0, const Inset * inset0)
49 Buffer * buf = const_cast<Buffer *>(buf0);
50 Inset * inset = const_cast<Inset *>(inset0);
51 DocIterator dit(buf, inset ? inset : &buf->inset());
57 DocIterator doc_iterator_end(const Buffer * buf0, const Inset * inset0)
59 Buffer * buf = const_cast<Buffer *>(buf0);
60 Inset * inset = const_cast<Inset *>(inset0);
61 return DocIterator(buf, inset ? inset : &buf->inset());
65 DocIterator DocIterator::clone(Buffer * buffer) const
67 LASSERT(buffer->isClone(), return DocIterator());
68 Inset * inset = &buffer->inset();
69 DocIterator dit(buffer);
70 size_t const n = slices_.size();
71 for (size_t i = 0 ; i != n; ++i) {
73 dit.push_back(slices_[i]);
74 dit.top().inset_ = inset;
76 inset = dit.nextInset();
82 bool DocIterator::inRegexped() const
84 InsetMath * im = inset().asInsetMath();
87 InsetMathHull * hull = im->asHullInset();
88 return hull && hull->getType() == hullRegexp;
92 LyXErr & operator<<(LyXErr & os, DocIterator const & it)
99 Inset * DocIterator::nextInset() const
101 LASSERT(!empty(), return nullptr);
102 if (pos() == lastpos())
104 if (pos() > lastpos()) {
105 LYXERR0("Should not happen, but it does: pos() = "
106 << pos() << ", lastpos() = " << lastpos());
110 return nextAtom().nucleus();
111 return paragraph().getInset(pos());
115 Inset * DocIterator::prevInset() const
117 LASSERT(!empty(), return nullptr);
122 // FIXME: this should not happen but it does.
124 // http://www.lyx.org/trac/ticket/3189
127 return prevAtom().nucleus();
129 return paragraph().getInset(pos() - 1);
133 Inset * DocIterator::realInset() const
135 LASSERT(inTexted(), return nullptr);
136 // if we are in a tabular, we need the cell
137 if (inset().lyxCode() == TABULAR_CODE) {
138 InsetTabular * tabular = inset().asInsetTabular();
139 return tabular->cell(idx()).get();
145 InsetMath & DocIterator::nextMath()
147 return *nextAtom().nucleus();
151 InsetMath & DocIterator::prevMath()
153 return *prevAtom().nucleus();
157 MathAtom & DocIterator::prevAtom() const
159 LASSERT(!empty(), /**/);
160 LASSERT(pos() > 0, /**/);
161 return cell()[pos() - 1];
165 MathAtom & DocIterator::nextAtom() const
167 LASSERT(!empty(), /**/);
168 //lyxerr << "lastpos: " << lastpos() << " next atom:\n" << *this << endl;
169 LASSERT(pos() < lastpos(), /**/);
170 return cell()[pos()];
174 Text * DocIterator::text() const
176 LASSERT(!empty(), return nullptr);
181 Paragraph & DocIterator::paragraph() const
187 return top().paragraph();
191 Paragraph & DocIterator::innerParagraph() const
194 return innerTextSlice().paragraph();
198 FontSpan DocIterator::locateWord(word_location const loc) const
200 FontSpan f = FontSpan();
202 if (!top().text()->empty()) {
204 top().paragraph().locateWord(f.first, f.last, loc);
210 CursorSlice const & DocIterator::innerTextSlice() const
213 // go up until first non-0 text is hit
214 // (innermost text is 0 in mathed)
215 for (int i = depth() - 1; i >= 0; --i)
216 if (slices_[i].text())
219 // This case is in principle not possible. We _must_
223 static const CursorSlice c;
228 docstring DocIterator::paragraphGotoArgument() const
230 CursorSlice const & s = innerTextSlice();
231 return convert<docstring>(s.paragraph().id()) + ' ' +
232 convert<docstring>(s.pos());
236 DocIterator DocIterator::getInnerText() const
238 DocIterator texted = *this;
239 while (!texted.inTexted())
245 pit_type DocIterator::lastpit() const
247 return inMathed() ? 0 : text()->paragraphs().size() - 1;
251 pos_type DocIterator::lastpos() const
253 return inMathed() ? cell().size() : paragraph().size();
257 idx_type DocIterator::lastidx() const
259 return top().lastidx();
263 size_t DocIterator::nargs() const
265 // assume 1x1 grid for main text
266 return top().nargs();
270 size_t DocIterator::ncols() const
272 // assume 1x1 grid for main text
273 return top().ncols();
277 size_t DocIterator::nrows() const
279 // assume 1x1 grid for main text
280 return top().nrows();
284 row_type DocIterator::row() const
290 col_type DocIterator::col() const
296 MathData & DocIterator::cell() const
298 // LASSERT(inMathed(), /**/);
303 Text * DocIterator::innerText() const
305 LASSERT(!empty(), return nullptr);
306 return innerTextSlice().text();
310 Inset * DocIterator::innerInsetOfType(int code) const
312 for (int i = depth() - 1; i >= 0; --i)
313 if (slices_[i].inset_->lyxCode() == code)
314 return slices_[i].inset_;
319 bool DocIterator::posBackward()
328 bool DocIterator::posForward()
330 if (pos() == lastpos())
337 // This duplicates code above, but is in the critical path.
338 // So please think twice before adding stuff
339 void DocIterator::forwardPos()
341 // this dog bites his tail
343 push_back(CursorSlice(*inset_));
347 CursorSlice & tip = top();
348 //lyxerr << "XXX\n" << *this << endl;
350 // not at cell/paragraph end?
351 if (tip.pos() != tip.lastpos()) {
352 // move into an inset to the right if possible
355 n = (tip.cell().begin() + tip.pos())->nucleus();
357 n = paragraph().getInset(tip.pos());
358 if (n && n->isActive()) {
359 //lyxerr << "... descend" << endl;
360 push_back(CursorSlice(*n));
365 // jump to the next cell/paragraph if possible
371 // otherwise leave inset and jump over inset as a whole
373 // 'tip' is invalid now...
379 void DocIterator::forwardPosIgnoreCollapsed()
381 Inset * const nextinset = nextInset();
382 // FIXME: the check for asInsetMath() shouldn't be necessary
383 // but math insets do not return a sensible editable() state yet.
384 if (nextinset && !nextinset->asInsetMath()
385 && !nextinset->editable()) {
393 void DocIterator::forwardPar()
397 while (!empty() && (!inTexted() || pos() != 0)) {
399 pos_type const lastp = lastpos();
400 Paragraph const & par = paragraph();
401 pos_type & pos = top().pos();
402 if (par.insetList().empty())
405 while (pos < lastp && !par.isInset(pos))
413 void DocIterator::forwardChar()
416 while (!empty() && pos() == lastpos())
421 void DocIterator::forwardInset()
425 while (!empty() && !nextInset()) {
427 pos_type const lastp = lastpos();
428 Paragraph const & par = paragraph();
429 pos_type & pos = top().pos();
430 while (pos < lastp && !par.isInset(pos))
440 void DocIterator::backwardChar()
443 while (!empty() && pos() == lastpos())
448 void DocIterator::backwardPos()
450 //this dog bites his tail
452 push_back(CursorSlice(*inset_));
453 top().idx() = lastidx();
454 top().pit() = lastpit();
455 top().pos() = lastpos();
459 // at inset beginning?
460 if (top().at_begin()) {
467 // entered another cell/paragraph from the right?
468 if (top().pos() == top().lastpos())
471 // move into an inset to the left if possible
474 n = (top().cell().begin() + top().pos())->nucleus();
476 n = paragraph().getInset(top().pos());
477 if (n && n->isActive()) {
478 push_back(CursorSlice(*n));
479 top().idx() = lastidx();
480 top().pit() = lastpit();
481 top().pos() = lastpos();
486 void DocIterator::backwardPosIgnoreCollapsed()
490 Inset const * ins = realInset();
491 if (ins && !ins->editable()) {
492 pop_back(); // move out of collapsed inset
499 // works, but currently not needed
500 void DocIterator::backwardInset()
504 while (!empty() && !nextInset()) {
506 pos_type const lastp = lastpos();
507 Paragraph const & par = paragraph();
508 pos_type & pos = top().pos();
509 while (pos > 0 && (pos == lastp || !par.isInset(pos)))
520 bool DocIterator::hasPart(DocIterator const & it) const
522 // it can't be a part if it is larger
523 if (it.depth() > depth())
526 // as inset adresses are the 'last' level
527 return &it.top().inset() == &slices_[it.depth() - 1].inset();
531 bool DocIterator::allowSpellCheck() const
533 /// spell check is disabled if the iterator position
534 /// is inside of an inset which disables the spell checker
535 size_t const n = depth();
536 for (size_t i = 0; i < n; ++i) {
537 if (!slices_[i].inset_->allowSpellCheck())
544 void DocIterator::updateInsets(Inset * inset)
546 // this function re-creates the cache of inset pointers.
547 //lyxerr << "converting:\n" << *this << endl;
548 DocIterator dit = *this;
549 size_t const n = slices_.size();
551 for (size_t i = 0 ; i < n; ++i) {
554 top().inset_ = inset;
558 //lyxerr << "converted:\n" << *this << endl;
562 bool DocIterator::fixIfBroken()
567 // Go through the slice stack from the bottom.
568 // Check that all coordinates (idx, pit, pos) are correct and
569 // that the inset is the one which is claimed to be there
570 Inset * inset = &slices_[0].inset();
572 size_t n = slices_.size();
573 for (; i != n; ++i) {
574 CursorSlice & cs = slices_[i];
575 if (&cs.inset() != inset || ! cs.inset().isActive()) {
576 // the whole slice is wrong, chop off this as well
578 LYXERR(Debug::DEBUG, "fixIfBroken(): inset changed");
580 } else if (cs.idx() > cs.lastidx()) {
581 cs.idx() = cs.lastidx();
582 cs.pit() = cs.lastpit();
583 cs.pos() = cs.lastpos();
584 LYXERR(Debug::DEBUG, "fixIfBroken(): idx fixed");
586 } else if (cs.pit() > cs.lastpit()) {
587 cs.pit() = cs.lastpit();
588 cs.pos() = cs.lastpos();
589 LYXERR(Debug::DEBUG, "fixIfBroken(): pit fixed");
591 } else if (cs.pos() > cs.lastpos()) {
592 cs.pos() = cs.lastpos();
593 LYXERR(Debug::DEBUG, "fixIfBroken(): pos fixed");
595 } else if (i != n - 1 && cs.pos() != cs.lastpos()) {
596 // get inset which is supposed to be in the next slice
597 if (cs.inset().inMathed())
598 inset = (cs.cell().begin() + cs.pos())->nucleus();
599 else if (Inset * csInset = cs.paragraph().getInset(cs.pos()))
602 // there are slices left, so there must be another inset
608 // Did we make it through the whole slice stack? Otherwise there
609 // was a problem at slice i, and we have to chop off above
611 LYXERR(Debug::DEBUG, "fixIfBroken(): cursor chopped at " << i);
619 void DocIterator::sanitize()
621 // keep a copy of the slices
622 vector<CursorSlice> const sl = slices_;
625 inset_ = &buffer_->inset();
626 Inset * inset = inset_;
627 // re-add the slices one by one, and adjust the inset pointer.
628 for (size_t i = 0, n = sl.size(); i != n; ++i) {
629 if (inset == nullptr) {
631 LYXERR0("Null inset on cursor stack.");
635 if (!inset->isActive()) {
636 LYXERR0("Inset found on cursor stack is not active.");
641 top().inset_ = inset;
650 bool DocIterator::isInside(Inset const * p) const
652 for (CursorSlice const & sl : slices_)
653 if (&sl.inset() == p)
659 void DocIterator::leaveInset(Inset const & inset)
661 for (size_t i = 0; i != slices_.size(); ++i) {
662 if (&slices_[i].inset() == &inset) {
670 int DocIterator::find(MathData const & cell) const
672 for (size_t l = 0; l != slices_.size(); ++l) {
673 if (slices_[l].asInsetMath() && &slices_[l].cell() == &cell)
680 int DocIterator::find(Inset const * inset) const
682 for (size_t l = 0; l != slices_.size(); ++l) {
683 if (&slices_[l].inset() == inset)
690 void DocIterator::cutOff(int above, vector<CursorSlice> & cut)
692 cut = vector<CursorSlice>(slices_.begin() + above + 1, slices_.end());
693 slices_.resize(above + 1);
697 void DocIterator::cutOff(int above)
699 slices_.resize(above + 1);
703 void DocIterator::append(vector<CursorSlice> const & x)
705 slices_.insert(slices_.end(), x.begin(), x.end());
709 void DocIterator::append(idx_type idx, pos_type pos)
711 slices_.push_back(CursorSlice());
717 docstring DocIterator::getPossibleLabel() const
719 return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
723 Encoding const * DocIterator::getEncoding() const
728 BufferParams const & bp = buffer()->params();
729 if (bp.useNonTeXFonts)
730 return encodings.fromLyXName("utf8-plain");
732 // With platex, we don't switch encodings (not even if forced).
733 if (bp.encoding().package() == Encoding::japanese)
734 return &bp.encoding();
736 CursorSlice const & sl = innerTextSlice();
737 Text const & text = *sl.text();
738 Language const * lang =
739 text.getPar(sl.pit()).getFont(bp, sl.pos(), text.outerFont(sl.pit())).language();
740 // If we have a custom encoding for the buffer, we don't switch
741 // encodings (see output_latex::switchEncoding())
742 bool const customenc = bp.inputenc != "auto-legacy" && bp.inputenc != "auto-legacy-plain";
743 Encoding const * enc = customenc ? &bp.encoding() : lang->encoding();
745 // Some insets force specific encodings sometimes (e.g., listings in
746 // multibyte context forces singlebyte).
747 if (inset().forcedEncoding(enc, encodings.fromLyXName("iso8859-1"))) {
748 // Get the language outside the inset
749 size_t const n = depth();
750 for (size_t i = 0; i < n; ++i) {
751 Text const & otext = *slices_[i].text();
752 Language const * olang =
753 otext.getPar(slices_[i].pit()).getFont(bp, slices_[i].pos(),
754 otext.outerFont(slices_[i].pit())).language();
755 Encoding const * oenc = olang->encoding();
756 if (oenc->name() != "inherit")
757 return inset().forcedEncoding(enc, oenc);
759 // Fall back to buffer encoding if no outer lang was found.
760 return inset().forcedEncoding(enc, &bp.encoding());
763 // Inherited encoding (latex_language) is determined by the context
764 // Look for the first outer encoding that is not itself "inherit"
765 if (lang->encoding()->name() == "inherit") {
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 // Again, if we have a custom encoding, this is used
773 // instead of the language's.
774 Encoding const * oenc = customenc ? &bp.encoding() : olang->encoding();
775 if (olang->encoding()->name() != "inherit")
784 ostream & operator<<(ostream & os, DocIterator const & dit)
786 for (size_t i = 0, n = dit.depth(); i != n; ++i)
787 os << " " << dit[i] << "\n";
792 ///////////////////////////////////////////////////////
794 StableDocIterator::StableDocIterator(DocIterator const & dit) :
795 data_(dit.internalData())
797 for (size_t i = 0, n = data_.size(); i != n; ++i)
798 data_[i].inset_ = nullptr;
802 DocIterator StableDocIterator::asDocIterator(Buffer * buf) const
804 DocIterator dit(buf);
811 ostream & operator<<(ostream & os, StableDocIterator const & dit)
813 for (size_t i = 0, n = dit.data_.size(); i != n; ++i)
814 os << " " << dit.data_[i] << "\n";
819 bool operator==(StableDocIterator const & dit1, StableDocIterator const & dit2)
821 return dit1.data_ == dit2.data_;