]> git.lyx.org Git - lyx.git/blob - src/DocIterator.cpp
Less expensive OP first as this might be called often.
[lyx.git] / src / DocIterator.cpp
1 /**
2  * \file DocIterator.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12
13 #include <config.h>
14
15 #include "DocIterator.h"
16
17 #include "Buffer.h"
18 #include "BufferParams.h"
19 #include "Encoding.h"
20 #include "Font.h"
21 #include "InsetList.h"
22 #include "Language.h"
23 #include "Paragraph.h"
24 #include "Text.h"
25
26 #include "mathed/MathData.h"
27 #include "mathed/InsetMath.h"
28 #include "mathed/InsetMathHull.h"
29
30 #include "insets/InsetTabular.h"
31
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"
38
39 #include <ostream>
40
41 using namespace std;
42 using namespace lyx::support;
43
44 namespace lyx {
45
46
47 DocIterator doc_iterator_begin(const Buffer * buf0, const Inset * inset0)
48 {
49         Buffer * buf = const_cast<Buffer *>(buf0);
50         Inset * inset = const_cast<Inset *>(inset0);
51         DocIterator dit(buf, inset ? inset : &buf->inset());
52         dit.forwardPos();
53         return dit;
54 }
55
56
57 DocIterator doc_iterator_end(const Buffer * buf0, const Inset * inset0)
58 {
59         Buffer * buf = const_cast<Buffer *>(buf0);
60         Inset * inset = const_cast<Inset *>(inset0);
61         return DocIterator(buf, inset ? inset : &buf->inset());
62 }
63
64
65 DocIterator DocIterator::clone(Buffer * buffer) const
66 {
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) {
72                 LBUFERR(inset);
73                 dit.push_back(slices_[i]);
74                 dit.top().inset_ = inset;
75                 if (i + 1 != n)
76                         inset = dit.nextInset();
77         }
78         return dit;
79 }
80
81
82 bool DocIterator::inRegexped() const
83 {
84         InsetMath * im = inset().asInsetMath();
85         if (!im)
86                 return false;
87         InsetMathHull * hull = im->asHullInset();
88         return hull && hull->getType() == hullRegexp;
89 }
90
91
92 LyXErr & operator<<(LyXErr & os, DocIterator const & it)
93 {
94         os.stream() << it;
95         return os;
96 }
97
98
99 Inset * DocIterator::nextInset() const
100 {
101         LASSERT(!empty(), return nullptr);
102         if (pos() == lastpos())
103                 return nullptr;
104         if (pos() > lastpos()) {
105                 LYXERR0("Should not happen, but it does: pos() = "
106                         << pos() << ", lastpos() = " << lastpos());
107                 return nullptr;
108         }
109         if (inMathed())
110                 return nextAtom().nucleus();
111         return paragraph().getInset(pos());
112 }
113
114
115 Inset * DocIterator::prevInset() const
116 {
117         LASSERT(!empty(), return nullptr);
118         if (pos() == 0)
119                 return nullptr;
120         if (inMathed()) {
121                 if (cell().empty())
122                         // FIXME: this should not happen but it does.
123                         // See bug 3189
124                         // http://www.lyx.org/trac/ticket/3189
125                         return nullptr;
126                 else
127                         return prevAtom().nucleus();
128         }
129         return paragraph().getInset(pos() - 1);
130 }
131
132
133 Inset * DocIterator::realInset() const
134 {
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();
140         }
141         return &inset();
142 }
143
144
145 InsetMath & DocIterator::nextMath()
146 {
147         return *nextAtom().nucleus();
148 }
149
150
151 InsetMath & DocIterator::prevMath()
152 {
153         return *prevAtom().nucleus();
154 }
155
156
157 MathAtom & DocIterator::prevAtom() const
158 {
159         LASSERT(!empty(), /**/);
160         LASSERT(pos() > 0, /**/);
161         return cell()[pos() - 1];
162 }
163
164
165 MathAtom & DocIterator::nextAtom() const
166 {
167         LASSERT(!empty(), /**/);
168         //lyxerr << "lastpos: " << lastpos() << " next atom:\n" << *this << endl;
169         LASSERT(pos() < lastpos(), /**/);
170         return cell()[pos()];
171 }
172
173
174 Text * DocIterator::text() const
175 {
176         LASSERT(!empty(), return nullptr);
177         return top().text();
178 }
179
180
181 Paragraph & DocIterator::paragraph() const
182 {
183         if (!inTexted()) {
184                 LYXERR0(*this);
185                 LBUFERR(false);
186         }
187         return top().paragraph();
188 }
189
190
191 Paragraph & DocIterator::innerParagraph() const
192 {
193         LBUFERR(!empty());
194         return innerTextSlice().paragraph();
195 }
196
197
198 FontSpan DocIterator::locateWord(word_location const loc) const
199 {
200         FontSpan f = FontSpan();
201
202         if (!top().text()->empty()) {
203                 f.first = pos();
204                 top().paragraph().locateWord(f.first, f.last, loc);
205         }
206         return f;
207 }
208
209
210 CursorSlice const & DocIterator::innerTextSlice() const
211 {
212         LBUFERR(!empty());
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())
217                         return slices_[i];
218
219         // This case is in principle not possible. We _must_
220         // be inside a Text.
221         LBUFERR(false);
222         // Squash warning
223         static const CursorSlice c;
224         return c;
225 }
226
227
228 docstring DocIterator::paragraphGotoArgument() const
229 {
230         CursorSlice const & s = innerTextSlice();
231         return convert<docstring>(s.paragraph().id()) + ' ' +
232                 convert<docstring>(s.pos());
233 }
234
235
236 DocIterator DocIterator::getInnerText() const
237 {
238         DocIterator texted = *this;
239         while (!texted.inTexted())
240                 texted.pop_back();
241         return texted;
242 }
243
244
245 pit_type DocIterator::lastpit() const
246 {
247         return inMathed() ? 0 : text()->paragraphs().size() - 1;
248 }
249
250
251 pos_type DocIterator::lastpos() const
252 {
253         return inMathed() ? cell().size() : paragraph().size();
254 }
255
256
257 idx_type DocIterator::lastidx() const
258 {
259         return top().lastidx();
260 }
261
262
263 size_t DocIterator::nargs() const
264 {
265         // assume 1x1 grid for main text
266         return top().nargs();
267 }
268
269
270 size_t DocIterator::ncols() const
271 {
272         // assume 1x1 grid for main text
273         return top().ncols();
274 }
275
276
277 size_t DocIterator::nrows() const
278 {
279         // assume 1x1 grid for main text
280         return top().nrows();
281 }
282
283
284 row_type DocIterator::row() const
285 {
286         return top().row();
287 }
288
289
290 col_type DocIterator::col() const
291 {
292         return top().col();
293 }
294
295
296 MathData & DocIterator::cell() const
297 {
298 //      LASSERT(inMathed(), /**/);
299         return top().cell();
300 }
301
302
303 Text * DocIterator::innerText() const
304 {
305         LASSERT(!empty(), return nullptr);
306         return innerTextSlice().text();
307 }
308
309
310 Inset * DocIterator::innerInsetOfType(int code) const
311 {
312         for (int i = depth() - 1; i >= 0; --i)
313                 if (slices_[i].inset_->lyxCode() == code)
314                         return slices_[i].inset_;
315         return nullptr;
316 }
317
318
319 bool DocIterator::posBackward()
320 {
321         if (pos() == 0)
322                 return false;
323         --pos();
324         return true;
325 }
326
327
328 bool DocIterator::posForward()
329 {
330         if (pos() == lastpos())
331                 return false;
332         ++pos();
333         return true;
334 }
335
336
337 // This duplicates code above, but is in the critical path.
338 // So please think twice before adding stuff
339 void DocIterator::forwardPos()
340 {
341         // this dog bites his tail
342         if (empty()) {
343                 push_back(CursorSlice(*inset_));
344                 return;
345         }
346
347         CursorSlice & tip = top();
348         //lyxerr << "XXX\n" << *this << endl;
349
350         // not at cell/paragraph end?
351         if (tip.pos() != tip.lastpos()) {
352                 // move into an inset to the right if possible
353                 Inset * n = nullptr;
354                 if (inMathed())
355                         n = (tip.cell().begin() + tip.pos())->nucleus();
356                 else
357                         n = paragraph().getInset(tip.pos());
358                 if (n && n->isActive()) {
359                         //lyxerr << "... descend" << endl;
360                         push_back(CursorSlice(*n));
361                         return;
362                 }
363         }
364
365         // jump to the next cell/paragraph if possible
366         if (!tip.at_end()) {
367                 tip.forwardPos();
368                 return;
369         }
370
371         // otherwise leave inset and jump over inset as a whole
372         pop_back();
373         // 'tip' is invalid now...
374         if (!empty())
375                 ++top().pos();
376 }
377
378
379 void DocIterator::forwardPosIgnoreCollapsed()
380 {
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()) {
386                 ++top().pos();
387                 return;
388         }
389         forwardPos();
390 }
391
392
393 void DocIterator::forwardPar()
394 {
395         forwardPos();
396
397         while (!empty() && (!inTexted() || pos() != 0)) {
398                 if (inTexted()) {
399                         pos_type const lastp = lastpos();
400                         Paragraph const & par = paragraph();
401                         pos_type & pos = top().pos();
402                         if (par.insetList().empty())
403                                 pos = lastp;
404                         else
405                                 while (pos < lastp && !par.isInset(pos))
406                                         ++pos;
407                 }
408                 forwardPos();
409         }
410 }
411
412
413 void DocIterator::forwardChar()
414 {
415         forwardPos();
416         while (!empty() && pos() == lastpos())
417                 forwardPos();
418 }
419
420
421 void DocIterator::forwardInset()
422 {
423         forwardPos();
424
425         while (!empty() && !nextInset()) {
426                 if (inTexted()) {
427                         pos_type const lastp = lastpos();
428                         Paragraph const & par = paragraph();
429                         pos_type & pos = top().pos();
430                         while (pos < lastp && !par.isInset(pos))
431                                 ++pos;
432                         if (pos < lastp)
433                                 break;
434                 }
435                 forwardPos();
436         }
437 }
438
439
440 void DocIterator::backwardChar()
441 {
442         backwardPos();
443         while (!empty() && pos() == lastpos())
444                 backwardPos();
445 }
446
447
448 void DocIterator::backwardPos()
449 {
450         //this dog bites his tail
451         if (empty()) {
452                 push_back(CursorSlice(*inset_));
453                 top().idx() = lastidx();
454                 top().pit() = lastpit();
455                 top().pos() = lastpos();
456                 return;
457         }
458
459         // at inset beginning?
460         if (top().at_begin()) {
461                 pop_back();
462                 return;
463         }
464
465         top().backwardPos();
466
467         // entered another cell/paragraph from the right?
468         if (top().pos() == top().lastpos())
469                 return;
470
471         // move into an inset to the left if possible
472         Inset * n = nullptr;
473         if (inMathed())
474                 n = (top().cell().begin() + top().pos())->nucleus();
475         else
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();
482         }
483 }
484
485
486 void DocIterator::backwardPosIgnoreCollapsed()
487 {
488         backwardPos();
489         if (inTexted()) {
490                 Inset const * ins = realInset();
491                 if (ins && !ins->editable()) {
492                         pop_back(); // move out of collapsed inset
493                 }
494         }
495 }
496
497
498 #if 0
499 // works, but currently not needed
500 void DocIterator::backwardInset()
501 {
502         backwardPos();
503
504         while (!empty() && !nextInset()) {
505                 if (inTexted()) {
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)))
510                                 --pos;
511                         if (pos > 0)
512                                 break;
513                 }
514                 backwardPos();
515         }
516 }
517 #endif
518
519
520 bool DocIterator::hasPart(DocIterator const & it) const
521 {
522         // it can't be a part if it is larger
523         if (it.depth() > depth())
524                 return false;
525
526         // as inset adresses are the 'last' level
527         return &it.top().inset() == &slices_[it.depth() - 1].inset();
528 }
529
530
531 bool DocIterator::allowSpellCheck() const
532 {
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())
538                         return false;
539         }
540         return true;
541 }
542
543
544 void DocIterator::updateInsets(Inset * inset)
545 {
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();
550         slices_.resize(0);
551         for (size_t i = 0 ; i < n; ++i) {
552                 if (dit[i].empty() && pos() > 0 && prevMath().lyxCode() == MATH_SCRIPT_CODE)
553                         // Workaround: With empty optional argument and a trailing script,
554                         // we have empty slices in math macro args (#11676)
555                         // FIXME: Find real cause!
556                         continue;
557                 LBUFERR(inset);
558                 push_back(dit[i]);
559                 top().inset_ = inset;
560                 if (i + 1 != n)
561                         inset = nextInset();
562         }
563         //lyxerr << "converted:\n" << *this << endl;
564 }
565
566
567 bool DocIterator::fixIfBroken()
568 {
569         if (empty())
570                 return false;
571
572         // Go through the slice stack from the bottom.
573         // Check that all coordinates (idx, pit, pos) are correct and
574         // that the inset is the one which is claimed to be there
575         Inset * inset = &slices_[0].inset();
576         size_t i = 0;
577         size_t n = slices_.size();
578         for (; i != n; ++i) {
579                 CursorSlice & cs = slices_[i];
580                 if (&cs.inset() != inset || ! cs.inset().isActive()) {
581                         // the whole slice is wrong, chop off this as well
582                         --i;
583                         LYXERR(Debug::DEBUG, "fixIfBroken(): inset changed");
584                         break;
585                 } else if (cs.idx() > cs.lastidx()) {
586                         cs.idx() = cs.lastidx();
587                         cs.pit() = cs.lastpit();
588                         cs.pos() = cs.lastpos();
589                         LYXERR(Debug::DEBUG, "fixIfBroken(): idx fixed");
590                         break;
591                 } else if (cs.pit() > cs.lastpit()) {
592                         cs.pit() = cs.lastpit();
593                         cs.pos() = cs.lastpos();
594                         LYXERR(Debug::DEBUG, "fixIfBroken(): pit fixed");
595                         break;
596                 } else if (cs.pos() > cs.lastpos()) {
597                         cs.pos() = cs.lastpos();
598                         LYXERR(Debug::DEBUG, "fixIfBroken(): pos fixed");
599                         break;
600                 } else if (i != n - 1 && cs.pos() != cs.lastpos()) {
601                         // get inset which is supposed to be in the next slice
602                         if (cs.inset().inMathed())
603                                 inset = (cs.cell().begin() + cs.pos())->nucleus();
604                         else if (Inset * csInset = cs.paragraph().getInset(cs.pos()))
605                                 inset = csInset;
606                         else {
607                                 // there are slices left, so there must be another inset
608                                 break;
609                         }
610                 }
611         }
612
613         // Did we make it through the whole slice stack? Otherwise there
614         // was a problem at slice i, and we have to chop off above
615         if (i < n) {
616                 LYXERR(Debug::DEBUG, "fixIfBroken(): cursor chopped at " << i);
617                 resize(i + 1);
618                 return true;
619         } else
620                 return false;
621 }
622
623
624 void DocIterator::sanitize()
625 {
626         // keep a copy of the slices
627         vector<CursorSlice> const sl = slices_;
628         slices_.clear();
629         if (buffer_)
630                 inset_ = &buffer_->inset();
631         Inset * inset = inset_;
632         // re-add the slices one by one, and adjust the inset pointer.
633         for (size_t i = 0, n = sl.size(); i != n; ++i) {
634                 if (inset == nullptr) {
635                         // FIXME
636                         LYXERR0("Null inset on cursor stack.");
637                         fixIfBroken();
638                         break;
639                 }
640                 if (!inset->isActive()) {
641                         LYXERR0("Inset found on cursor stack is not active.");
642                         fixIfBroken();
643                         break;
644                 }
645                 push_back(sl[i]);
646                 top().inset_ = inset;
647                 if (fixIfBroken())
648                         break;
649                 if (i + 1 != n)
650                         inset = nextInset();
651         }
652 }
653
654
655 bool DocIterator::isInside(Inset const * p) const
656 {
657         for (CursorSlice const & sl : slices_)
658                 if (&sl.inset() == p)
659                         return true;
660         return false;
661 }
662
663
664 void DocIterator::leaveInset(Inset const & inset)
665 {
666         for (size_t i = 0; i != slices_.size(); ++i) {
667                 if (&slices_[i].inset() == &inset) {
668                         resize(i);
669                         return;
670                 }
671         }
672 }
673
674
675 int DocIterator::find(MathData const & cell) const
676 {
677         for (size_t l = 0; l != slices_.size(); ++l) {
678                 if (slices_[l].asInsetMath() && &slices_[l].cell() == &cell)
679                         return l;
680         }
681         return -1;
682 }
683
684
685 int DocIterator::find(Inset const * inset) const
686 {
687         for (size_t l = 0; l != slices_.size(); ++l) {
688                 if (&slices_[l].inset() == inset)
689                         return l;
690         }
691         return -1;
692 }
693
694
695 void DocIterator::cutOff(int above, vector<CursorSlice> & cut)
696 {
697         cut = vector<CursorSlice>(slices_.begin() + above + 1, slices_.end());
698         slices_.resize(above + 1);
699 }
700
701
702 void DocIterator::cutOff(int above)
703 {
704         slices_.resize(above + 1);
705 }
706
707
708 void DocIterator::append(vector<CursorSlice> const & x)
709 {
710         slices_.insert(slices_.end(), x.begin(), x.end());
711 }
712
713
714 void DocIterator::append(idx_type idx, pos_type pos)
715 {
716         slices_.push_back(CursorSlice());
717         top().idx() = idx;
718         top().pos() = pos;
719 }
720
721
722 docstring DocIterator::getPossibleLabel() const
723 {
724         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
725 }
726
727
728 Encoding const * DocIterator::getEncoding() const
729 {
730         if (empty())
731                 return nullptr;
732
733         BufferParams const & bp = buffer()->params();
734         if (bp.useNonTeXFonts)
735                 return encodings.fromLyXName("utf8-plain");
736
737         // With platex, we don't switch encodings (not even if forced).
738         if (bp.encoding().package() == Encoding::japanese)
739                 return &bp.encoding();
740
741         CursorSlice const & sl = innerTextSlice();
742         Text const & text = *sl.text();
743         Language const * lang =
744                 text.getPar(sl.pit()).getFont(bp, sl.pos(), text.outerFont(sl.pit())).language();
745         // If we have a custom encoding for the buffer, we don't switch
746         // encodings (see output_latex::switchEncoding())
747         bool const customenc = bp.inputenc != "auto-legacy" && bp.inputenc != "auto-legacy-plain";
748         Encoding const * enc = customenc ? &bp.encoding() : lang->encoding();
749
750         // Some insets force specific encodings sometimes (e.g., listings in
751         // multibyte context forces singlebyte).
752         if (inset().forcedEncoding(enc, encodings.fromLyXName("iso8859-1"))) {
753                 // Get the language outside the inset
754                 size_t const n = depth();
755                 for (size_t i = 0; i < n; ++i) {
756                         Text const & otext = *slices_[i].text();
757                         Language const * olang =
758                                         otext.getPar(slices_[i].pit()).getFont(bp, slices_[i].pos(),
759                                                                                otext.outerFont(slices_[i].pit())).language();
760                         Encoding const * oenc = olang->encoding();
761                         if (oenc->name() != "inherit")
762                                 return inset().forcedEncoding(enc, oenc);
763                 }
764                 // Fall back to buffer encoding if no outer lang was found.
765                 return inset().forcedEncoding(enc, &bp.encoding());
766         }
767
768         // Inherited encoding (latex_language) is determined by the context
769         // Look for the first outer encoding that is not itself "inherit"
770         if (lang->encoding()->name() == "inherit") {
771                 size_t const n = depth();
772                 for (size_t i = 0; i < n; ++i) {
773                         Text const & otext = *slices_[i].text();
774                         Language const * olang =
775                                         otext.getPar(slices_[i].pit()).getFont(bp, slices_[i].pos(),
776                                                                                otext.outerFont(slices_[i].pit())).language();
777                         // Again, if we have a custom encoding, this is used
778                         // instead of the language's.
779                         Encoding const * oenc = customenc ? &bp.encoding() : olang->encoding();
780                         if (olang->encoding()->name() != "inherit")
781                                 return oenc;
782                 }
783         }
784
785         return enc;
786 }
787
788
789 ostream & operator<<(ostream & os, DocIterator const & dit)
790 {
791         for (size_t i = 0, n = dit.depth(); i != n; ++i)
792                 os << " " << dit[i] << "\n";
793         return os;
794 }
795
796
797 ///////////////////////////////////////////////////////
798
799 StableDocIterator::StableDocIterator(DocIterator const & dit) :
800         data_(dit.internalData())
801 {
802         for (size_t i = 0, n = data_.size(); i != n; ++i)
803                 data_[i].inset_ = nullptr;
804 }
805
806
807 DocIterator StableDocIterator::asDocIterator(Buffer * buf) const
808 {
809         DocIterator dit(buf);
810         dit.slices_ = data_;
811         dit.sanitize();
812         return dit;
813 }
814
815
816 ostream & operator<<(ostream & os, StableDocIterator const & dit)
817 {
818         for (size_t i = 0, n = dit.data_.size(); i != n; ++i)
819                 os << " " << dit.data_[i] << "\n";
820         return os;
821 }
822
823
824 bool operator==(StableDocIterator const & dit1, StableDocIterator const & dit2)
825 {
826         return dit1.data_ == dit2.data_;
827 }
828
829
830 } // namespace lyx