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 "LaTeXFeatures.h"
24 #include "Paragraph.h"
28 #include "mathed/MathData.h"
29 #include "mathed/InsetMath.h"
30 #include "mathed/InsetMathHull.h"
32 #include "insets/InsetTabular.h"
34 #include "support/convert.h"
35 #include "support/debug.h"
36 #include "support/ExceptionMessage.h"
37 #include "support/gettext.h"
38 #include "support/lassert.h"
39 #include "support/lstrings.h"
44 using namespace lyx::support;
49 DocIterator::DocIterator()
50 : boundary_(false), inset_(0), buffer_(0)
54 // We could be able to get rid of this if only every BufferView were
55 // associated to a buffer on construction.
56 DocIterator::DocIterator(Buffer * buf)
57 : boundary_(false), inset_(0), buffer_(buf)
61 DocIterator::DocIterator(Buffer * buf, Inset * inset)
62 : boundary_(false), inset_(inset), buffer_(buf)
66 DocIterator doc_iterator_begin(const Buffer * buf0, const Inset * inset0)
68 Buffer * buf = const_cast<Buffer *>(buf0);
69 Inset * inset = const_cast<Inset *>(inset0);
70 DocIterator dit(buf, inset ? inset : &buf->inset());
76 DocIterator doc_iterator_end(const Buffer * buf0, const Inset * inset0)
78 Buffer * buf = const_cast<Buffer *>(buf0);
79 Inset * inset = const_cast<Inset *>(inset0);
80 return DocIterator(buf, inset ? inset : &buf->inset());
84 DocIterator DocIterator::clone(Buffer * buffer) const
86 LASSERT(buffer->isClone(), return DocIterator());
87 Inset * inset = &buffer->inset();
88 DocIterator dit(buffer);
89 size_t const n = slices_.size();
90 for (size_t i = 0 ; i != n; ++i) {
92 dit.push_back(slices_[i]);
93 dit.top().inset_ = inset;
95 inset = dit.nextInset();
101 bool DocIterator::inRegexped() const
103 InsetMath * im = inset().asInsetMath();
106 InsetMathHull * hull = im->asHullInset();
107 return hull && hull->getType() == hullRegexp;
111 LyXErr & operator<<(LyXErr & os, DocIterator const & it)
118 Inset * DocIterator::nextInset() const
120 LASSERT(!empty(), return 0);
121 if (pos() == lastpos())
123 if (pos() > lastpos()) {
124 LYXERR0("Should not happen, but it does: pos() = "
125 << pos() << ", lastpos() = " << lastpos());
129 return nextAtom().nucleus();
130 return paragraph().getInset(pos());
134 Inset * DocIterator::prevInset() const
136 LASSERT(!empty(), return 0);
141 // FIXME: this should not happen but it does.
143 // http://www.lyx.org/trac/ticket/3189
146 return prevAtom().nucleus();
148 return paragraph().getInset(pos() - 1);
152 Inset * DocIterator::realInset() const
154 LASSERT(inTexted(), return 0);
155 // if we are in a tabular, we need the cell
156 if (inset().lyxCode() == TABULAR_CODE) {
157 InsetTabular * tabular = inset().asInsetTabular();
158 return tabular->cell(idx()).get();
164 MathAtom & DocIterator::prevAtom() const
166 LASSERT(!empty(), /**/);
167 LASSERT(pos() > 0, /**/);
168 return cell()[pos() - 1];
172 MathAtom & DocIterator::nextAtom() const
174 LASSERT(!empty(), /**/);
175 //lyxerr << "lastpos: " << lastpos() << " next atom:\n" << *this << endl;
176 LASSERT(pos() < lastpos(), /**/);
177 return cell()[pos()];
181 Text * DocIterator::text() const
183 LASSERT(!empty(), return 0);
188 Paragraph & DocIterator::paragraph() const
194 return top().paragraph();
198 Paragraph & DocIterator::innerParagraph() const
201 return innerTextSlice().paragraph();
205 FontSpan DocIterator::locateWord(word_location const loc) const
207 FontSpan f = FontSpan();
209 if (!top().text()->empty()) {
211 top().paragraph().locateWord(f.first, f.last, loc);
217 CursorSlice const & DocIterator::innerTextSlice() const
220 // go up until first non-0 text is hit
221 // (innermost text is 0 in mathed)
222 for (int i = depth() - 1; i >= 0; --i)
223 if (slices_[i].text())
226 // This case is in principle not possible. We _must_
230 static const CursorSlice c;
235 docstring DocIterator::paragraphGotoArgument() const
237 CursorSlice const & s = innerTextSlice();
238 return convert<docstring>(s.paragraph().id()) + ' ' +
239 convert<docstring>(s.pos());
243 DocIterator DocIterator::getInnerText() const
245 DocIterator texted = *this;
246 while (!texted.inTexted())
252 pit_type DocIterator::lastpit() const
254 return inMathed() ? 0 : text()->paragraphs().size() - 1;
258 pos_type DocIterator::lastpos() const
260 return inMathed() ? cell().size() : paragraph().size();
264 DocIterator::idx_type DocIterator::lastidx() const
266 return top().lastidx();
270 size_t DocIterator::nargs() const
272 // assume 1x1 grid for main text
273 return top().nargs();
277 size_t DocIterator::ncols() const
279 // assume 1x1 grid for main text
280 return top().ncols();
284 size_t DocIterator::nrows() const
286 // assume 1x1 grid for main text
287 return top().nrows();
291 DocIterator::row_type DocIterator::row() const
297 DocIterator::col_type DocIterator::col() const
303 MathData & DocIterator::cell() const
305 // LASSERT(inMathed(), /**/);
310 Text * DocIterator::innerText() const
312 LASSERT(!empty(), return 0);
313 return innerTextSlice().text();
317 Inset * DocIterator::innerInsetOfType(int code) const
319 for (int i = depth() - 1; i >= 0; --i)
320 if (slices_[i].inset_->lyxCode() == code)
321 return slices_[i].inset_;
326 bool DocIterator::posBackward()
335 bool DocIterator::posForward()
337 if (pos() == lastpos())
344 // This duplicates code above, but is in the critical path.
345 // So please think twice before adding stuff
346 void DocIterator::forwardPos()
348 // this dog bites his tail
350 push_back(CursorSlice(*inset_));
354 CursorSlice & tip = top();
355 //lyxerr << "XXX\n" << *this << endl;
357 // not at cell/paragraph end?
358 if (tip.pos() != tip.lastpos()) {
359 // move into an inset to the right if possible
362 n = (tip.cell().begin() + tip.pos())->nucleus();
364 n = paragraph().getInset(tip.pos());
365 if (n && n->isActive()) {
366 //lyxerr << "... descend" << endl;
367 push_back(CursorSlice(*n));
372 // jump to the next cell/paragraph if possible
378 // otherwise leave inset and jump over inset as a whole
380 // 'tip' is invalid now...
386 void DocIterator::forwardPosIgnoreCollapsed()
388 Inset * const nextinset = nextInset();
389 // FIXME: the check for asInsetMath() shouldn't be necessary
390 // but math insets do not return a sensible editable() state yet.
391 if (nextinset && !nextinset->asInsetMath()
392 && !nextinset->editable()) {
400 void DocIterator::forwardPar()
404 while (!empty() && (!inTexted() || pos() != 0)) {
406 pos_type const lastp = lastpos();
407 Paragraph const & par = paragraph();
408 pos_type & pos = top().pos();
409 if (par.insetList().empty())
412 while (pos < lastp && !par.isInset(pos))
420 void DocIterator::forwardChar()
423 while (!empty() && pos() == lastpos())
428 void DocIterator::forwardInset()
432 while (!empty() && !nextInset()) {
434 pos_type const lastp = lastpos();
435 Paragraph const & par = paragraph();
436 pos_type & pos = top().pos();
437 while (pos < lastp && !par.isInset(pos))
447 void DocIterator::backwardChar()
450 while (!empty() && pos() == lastpos())
455 void DocIterator::backwardPos()
457 //this dog bites his tail
459 push_back(CursorSlice(*inset_));
460 top().idx() = lastidx();
461 top().pit() = lastpit();
462 top().pos() = lastpos();
466 // at inset beginning?
467 if (top().at_begin()) {
474 // entered another cell/paragraph from the right?
475 if (top().pos() == top().lastpos())
478 // move into an inset to the left if possible
481 n = (top().cell().begin() + top().pos())->nucleus();
483 n = paragraph().getInset(top().pos());
484 if (n && n->isActive()) {
485 push_back(CursorSlice(*n));
486 top().idx() = lastidx();
487 top().pit() = lastpit();
488 top().pos() = lastpos();
494 // works, but currently not needed
495 void DocIterator::backwardInset()
499 while (!empty() && !nextInset()) {
501 pos_type const lastp = lastpos();
502 Paragraph const & par = paragraph();
503 pos_type & pos = top().pos();
504 while (pos > 0 && (pos == lastp || !par.isInset(pos)))
515 bool DocIterator::hasPart(DocIterator const & it) const
517 // it can't be a part if it is larger
518 if (it.depth() > depth())
521 // as inset adresses are the 'last' level
522 return &it.top().inset() == &slices_[it.depth() - 1].inset();
526 bool DocIterator::allowSpellCheck() const
528 /// spell check is disabled if the iterator position
529 /// is inside of an inset which disables the spell checker
530 size_t const n = depth();
531 for (size_t i = 0; i < n; ++i) {
532 if (!slices_[i].inset_->allowSpellCheck())
539 void DocIterator::updateInsets(Inset * inset)
541 // this function re-creates the cache of inset pointers.
542 //lyxerr << "converting:\n" << *this << endl;
543 DocIterator dit = *this;
544 size_t const n = slices_.size();
546 for (size_t i = 0 ; i < n; ++i) {
549 top().inset_ = inset;
553 //lyxerr << "converted:\n" << *this << endl;
557 bool DocIterator::fixIfBroken()
562 // Go through the slice stack from the bottom.
563 // Check that all coordinates (idx, pit, pos) are correct and
564 // that the inset is the one which is claimed to be there
565 Inset * inset = &slices_[0].inset();
567 size_t n = slices_.size();
568 for (; i != n; ++i) {
569 CursorSlice & cs = slices_[i];
570 if (&cs.inset() != inset || ! cs.inset().isActive()) {
571 // the whole slice is wrong, chop off this as well
573 LYXERR(Debug::DEBUG, "fixIfBroken(): inset changed");
575 } else if (cs.idx() > cs.lastidx()) {
576 cs.idx() = cs.lastidx();
577 cs.pit() = cs.lastpit();
578 cs.pos() = cs.lastpos();
579 LYXERR(Debug::DEBUG, "fixIfBroken(): idx fixed");
581 } else if (cs.pit() > cs.lastpit()) {
582 cs.pit() = cs.lastpit();
583 cs.pos() = cs.lastpos();
584 LYXERR(Debug::DEBUG, "fixIfBroken(): pit fixed");
586 } else if (cs.pos() > cs.lastpos()) {
587 cs.pos() = cs.lastpos();
588 LYXERR(Debug::DEBUG, "fixIfBroken(): pos fixed");
590 } else if (i != n - 1 && cs.pos() != cs.lastpos()) {
591 // get inset which is supposed to be in the next slice
592 if (cs.inset().inMathed())
593 inset = (cs.cell().begin() + cs.pos())->nucleus();
594 else if (Inset * csInset = cs.paragraph().getInset(cs.pos()))
597 // there are slices left, so there must be another inset
603 // Did we make it through the whole slice stack? Otherwise there
604 // was a problem at slice i, and we have to chop off above
606 LYXERR(Debug::DEBUG, "fixIfBroken(): cursor chopped at " << i);
614 void DocIterator::sanitize()
616 // keep a copy of the slices
617 vector<CursorSlice> const sl = slices_;
620 inset_ = &buffer_->inset();
621 Inset * inset = inset_;
622 // re-add the slices one by one, and adjust the inset pointer.
623 for (size_t i = 0, n = sl.size(); i != n; ++i) {
626 LYXERR0("Null inset on cursor stack.");
630 if (!inset->isActive()) {
631 LYXERR0("Inset found on cursor stack is not active.");
636 top().inset_ = inset;
645 int DocIterator::find(MathData const & cell) const
647 for (size_t l = 0; l != slices_.size(); ++l) {
648 if (slices_[l].asInsetMath() && &slices_[l].cell() == &cell)
655 int DocIterator::find(Inset const * inset) const
657 for (size_t l = 0; l != slices_.size(); ++l) {
658 if (&slices_[l].inset() == inset)
665 void DocIterator::cutOff(int above, vector<CursorSlice> & cut)
667 cut = vector<CursorSlice>(slices_.begin() + above + 1, slices_.end());
668 slices_.resize(above + 1);
672 void DocIterator::cutOff(int above)
674 slices_.resize(above + 1);
678 void DocIterator::append(vector<CursorSlice> const & x)
680 slices_.insert(slices_.end(), x.begin(), x.end());
684 void DocIterator::append(DocIterator::idx_type idx, pos_type pos)
686 slices_.push_back(CursorSlice());
692 Encoding const * DocIterator::getEncoding() const
697 BufferParams const & bp = buffer()->params();
698 if (bp.useNonTeXFonts)
699 return encodings.fromLyXName("utf8-plain");
701 CursorSlice const & sl = innerTextSlice();
702 Text const & text = *sl.text();
703 Language const * lang =
704 text.getPar(sl.pit()).getFont(bp, sl.pos(),
705 text.outerFont(sl.pit())).language();
706 // If we have a custom encoding for the buffer, we do not switch encoding ...
707 bool const customenc =
708 bp.inputenc != "auto" && bp.inputenc != "default";
709 // ... except for non-CJKutf8 CJK (see output_latex::switchEncoding())
710 bool const cjk_non_utf8 =
711 bp.encoding().name() != "utf8-cjk"
712 || !LaTeXFeatures::isAvailable("CJKutf8");
713 Encoding const * enc =
715 && (lang->encoding()->package() != Encoding::CJK || !cjk_non_utf8))
716 ? &bp.encoding() : lang->encoding();
718 // Some insets force specific encodings sometimes (e.g., listings in
719 // multibyte context forces singlebyte).
720 if (inset().forcedEncoding(enc, encodings.fromLyXName("iso8859-1"))) {
721 // Get the language outside the inset
722 size_t const n = depth();
723 for (size_t i = 0; i < n; ++i) {
724 Text const & otext = *slices_[i].text();
725 Language const * olang =
726 otext.getPar(slices_[i].pit()).getFont(bp, slices_[i].pos(),
727 otext.outerFont(slices_[i].pit())).language();
728 Encoding const * oenc = olang->encoding();
729 if (oenc->name() != "inherit")
730 return inset().forcedEncoding(enc, oenc);
732 // Fall back to buffer encoding if no outer lang was found.
733 return inset().forcedEncoding(enc, &bp.encoding());
736 // Inherited encoding (latex_language) is determined by the context
737 // Look for the first outer encoding that is not itself "inherit"
738 if (lang->encoding()->name() == "inherit") {
739 size_t const n = depth();
740 for (size_t i = 0; i < n; ++i) {
741 Text const & otext = *slices_[i].text();
742 Language const * olang =
743 otext.getPar(slices_[i].pit()).getFont(bp, slices_[i].pos(),
744 otext.outerFont(slices_[i].pit())).language();
745 // Again, if we have a custom encoding, this is used
746 // instead of the language's.
747 Encoding const * oenc =
749 && (olang->encoding()->package() != Encoding::CJK || !cjk_non_utf8))
750 ? &bp.encoding() : olang->encoding();
751 if (olang->encoding()->name() != "inherit")
760 ostream & operator<<(ostream & os, DocIterator const & dit)
762 for (size_t i = 0, n = dit.depth(); i != n; ++i)
763 os << " " << dit[i] << "\n";
768 ///////////////////////////////////////////////////////
770 StableDocIterator::StableDocIterator(DocIterator const & dit) :
771 data_(dit.internalData())
773 for (size_t i = 0, n = data_.size(); i != n; ++i)
778 DocIterator StableDocIterator::asDocIterator(Buffer * buf) const
780 DocIterator dit(buf);
787 ostream & operator<<(ostream & os, StableDocIterator const & dit)
789 for (size_t i = 0, n = dit.data_.size(); i != n; ++i)
790 os << " " << dit.data_[i] << "\n";
795 bool operator==(StableDocIterator const & dit1, StableDocIterator const & dit2)
797 return dit1.data_ == dit2.data_;