]> git.lyx.org Git - lyx.git/blob - src/DocIterator.cpp
Avoid full metrics computation with Update:FitCursor
[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 void DocIterator::backwardInset()
499 {
500         backwardPos();
501
502         while (!empty() && !nextInset()) {
503                 if (inTexted()) {
504                         pos_type const lastp = lastpos();
505                         Paragraph const & par = paragraph();
506                         pos_type & pos = top().pos();
507                         while (pos > 0 && (pos == lastp || !par.isInset(pos)))
508                                 --pos;
509                         if (pos > 0)
510                                 break;
511                 }
512                 backwardPos();
513         }
514 }
515
516
517 bool DocIterator::hasPart(DocIterator const & it) const
518 {
519         // it can't be a part if it is larger
520         if (it.depth() > depth())
521                 return false;
522
523         // as inset adresses are the 'last' level
524         return &it.top().inset() == &slices_[it.depth() - 1].inset();
525 }
526
527
528 bool DocIterator::allowSpellCheck() const
529 {
530         /// spell check is disabled if the iterator position
531         /// is inside of an inset which disables the spell checker
532         size_t const n = depth();
533         for (size_t i = 0; i < n; ++i) {
534                 if (!slices_[i].inset_->allowSpellCheck())
535                         return false;
536         }
537         return true;
538 }
539
540
541 void DocIterator::updateInsets(Inset * inset)
542 {
543         // this function re-creates the cache of inset pointers.
544         //lyxerr << "converting:\n" << *this << endl;
545         DocIterator dit = *this;
546         size_t const n = slices_.size();
547         slices_.resize(0);
548         for (size_t i = 0 ; i < n; ++i) {
549                 if (dit[i].empty() && pos() > 0 && prevMath().lyxCode() == MATH_SCRIPT_CODE)
550                         // Workaround: With empty optional argument and a trailing script,
551                         // we have empty slices in math macro args (#11676)
552                         // FIXME: Find real cause!
553                         continue;
554                 LBUFERR(inset);
555                 push_back(dit[i]);
556                 top().inset_ = inset;
557                 if (i + 1 != n)
558                         inset = nextInset();
559         }
560         //lyxerr << "converted:\n" << *this << endl;
561 }
562
563
564 bool DocIterator::fixIfBroken()
565 {
566         if (empty())
567                 return false;
568
569         // Go through the slice stack from the bottom.
570         // Check that all coordinates (idx, pit, pos) are correct and
571         // that the inset is the one which is claimed to be there
572         Inset * inset = &slices_[0].inset();
573         size_t i = 0;
574         size_t n = slices_.size();
575         for (; i != n; ++i) {
576                 CursorSlice & cs = slices_[i];
577                 if (&cs.inset() != inset || ! cs.inset().isActive()) {
578                         // the whole slice is wrong, chop off this as well
579                         --i;
580                         LYXERR(Debug::DEBUG, "fixIfBroken(): inset changed");
581                         break;
582                 } else if (cs.idx() > cs.lastidx()) {
583                         cs.idx() = cs.lastidx();
584                         cs.pit() = cs.lastpit();
585                         cs.pos() = cs.lastpos();
586                         LYXERR(Debug::DEBUG, "fixIfBroken(): idx fixed");
587                         break;
588                 } else if (cs.pit() > cs.lastpit()) {
589                         cs.pit() = cs.lastpit();
590                         cs.pos() = cs.lastpos();
591                         LYXERR(Debug::DEBUG, "fixIfBroken(): pit fixed");
592                         break;
593                 } else if (cs.pos() > cs.lastpos()) {
594                         cs.pos() = cs.lastpos();
595                         LYXERR(Debug::DEBUG, "fixIfBroken(): pos fixed");
596                         break;
597                 } else if (i != n - 1 && cs.pos() != cs.lastpos()) {
598                         // get inset which is supposed to be in the next slice
599                         if (cs.inset().inMathed())
600                                 inset = (cs.cell().begin() + cs.pos())->nucleus();
601                         else if (Inset * csInset = cs.paragraph().getInset(cs.pos()))
602                                 inset = csInset;
603                         else {
604                                 // there are slices left, so there must be another inset
605                                 break;
606                         }
607                 }
608         }
609
610         // Did we make it through the whole slice stack? Otherwise there
611         // was a problem at slice i, and we have to chop off above
612         if (i < n) {
613                 LYXERR(Debug::DEBUG, "fixIfBroken(): cursor chopped at " << i);
614                 resize(i + 1);
615                 return true;
616         } else
617                 return false;
618 }
619
620
621 void DocIterator::sanitize()
622 {
623         // keep a copy of the slices
624         vector<CursorSlice> const sl = slices_;
625         slices_.clear();
626         if (buffer_)
627                 inset_ = &buffer_->inset();
628         Inset * inset = inset_;
629         // re-add the slices one by one, and adjust the inset pointer.
630         for (size_t i = 0, n = sl.size(); i != n; ++i) {
631                 if (inset == nullptr) {
632                         // FIXME
633                         LYXERR0("Null inset on cursor stack.");
634                         fixIfBroken();
635                         break;
636                 }
637                 if (!inset->isActive()) {
638                         LYXERR0("Inset found on cursor stack is not active.");
639                         fixIfBroken();
640                         break;
641                 }
642                 push_back(sl[i]);
643                 top().inset_ = inset;
644                 if (fixIfBroken())
645                         break;
646                 if (i + 1 != n)
647                         inset = nextInset();
648         }
649 }
650
651
652 bool DocIterator::isInside(Inset const * p) const
653 {
654         for (CursorSlice const & sl : slices_)
655                 if (&sl.inset() == p)
656                         return true;
657         return false;
658 }
659
660
661 void DocIterator::leaveInset(Inset const & inset)
662 {
663         for (size_t i = 0; i != slices_.size(); ++i) {
664                 if (&slices_[i].inset() == &inset) {
665                         resize(i);
666                         return;
667                 }
668         }
669 }
670
671
672 int DocIterator::find(MathData const & cell) const
673 {
674         for (size_t l = 0; l != slices_.size(); ++l) {
675                 if (slices_[l].asInsetMath() && &slices_[l].cell() == &cell)
676                         return l;
677         }
678         return -1;
679 }
680
681
682 int DocIterator::find(Inset const * inset) const
683 {
684         for (size_t l = 0; l != slices_.size(); ++l) {
685                 if (&slices_[l].inset() == inset)
686                         return l;
687         }
688         return -1;
689 }
690
691
692 void DocIterator::cutOff(int above, vector<CursorSlice> & cut)
693 {
694         cut = vector<CursorSlice>(slices_.begin() + above + 1, slices_.end());
695         slices_.resize(above + 1);
696 }
697
698
699 void DocIterator::cutOff(int above)
700 {
701         slices_.resize(above + 1);
702 }
703
704
705 void DocIterator::append(vector<CursorSlice> const & x)
706 {
707         slices_.insert(slices_.end(), x.begin(), x.end());
708 }
709
710
711 void DocIterator::append(idx_type idx, pos_type pos)
712 {
713         slices_.push_back(CursorSlice());
714         top().idx() = idx;
715         top().pos() = pos;
716 }
717
718
719 docstring DocIterator::getPossibleLabel() const
720 {
721         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
722 }
723
724
725 Encoding const * DocIterator::getEncoding() const
726 {
727         if (empty())
728                 return nullptr;
729
730         BufferParams const & bp = buffer()->params();
731         if (bp.useNonTeXFonts)
732                 return encodings.fromLyXName("utf8-plain");
733
734         // With platex, we don't switch encodings (not even if forced).
735         if (bp.encoding().package() == Encoding::japanese)
736                 return &bp.encoding();
737
738         CursorSlice const & sl = innerTextSlice();
739         Text const & text = *sl.text();
740         Language const * lang =
741                 text.getPar(sl.pit()).getFont(bp, sl.pos(), text.outerFont(sl.pit())).language();
742         // If we have a custom encoding for the buffer, we don't switch
743         // encodings (see output_latex::switchEncoding())
744         bool const customenc = bp.inputenc != "auto-legacy" && bp.inputenc != "auto-legacy-plain";
745         Encoding const * enc = customenc ? &bp.encoding() : lang->encoding();
746
747         // Some insets force specific encodings sometimes (e.g., listings in
748         // multibyte context forces singlebyte).
749         if (inset().forcedEncoding(enc, encodings.fromLyXName("iso8859-1"))) {
750                 // Get the language outside the inset
751                 size_t const n = depth();
752                 for (size_t i = 0; i < n; ++i) {
753                         Text const & otext = *slices_[i].text();
754                         Language const * olang =
755                                         otext.getPar(slices_[i].pit()).getFont(bp, slices_[i].pos(),
756                                                                                otext.outerFont(slices_[i].pit())).language();
757                         Encoding const * oenc = olang->encoding();
758                         if (oenc->name() != "inherit")
759                                 return inset().forcedEncoding(enc, oenc);
760                 }
761                 // Fall back to buffer encoding if no outer lang was found.
762                 return inset().forcedEncoding(enc, &bp.encoding());
763         }
764
765         // Inherited encoding (latex_language) is determined by the context
766         // Look for the first outer encoding that is not itself "inherit"
767         if (lang->encoding()->name() == "inherit") {
768                 size_t const n = depth();
769                 for (size_t i = 0; i < n; ++i) {
770                         Text const & otext = *slices_[i].text();
771                         Language const * olang =
772                                         otext.getPar(slices_[i].pit()).getFont(bp, slices_[i].pos(),
773                                                                                otext.outerFont(slices_[i].pit())).language();
774                         // Again, if we have a custom encoding, this is used
775                         // instead of the language's.
776                         Encoding const * oenc = customenc ? &bp.encoding() : olang->encoding();
777                         if (olang->encoding()->name() != "inherit")
778                                 return oenc;
779                 }
780         }
781
782         return enc;
783 }
784
785
786 ostream & operator<<(ostream & os, DocIterator const & dit)
787 {
788         for (size_t i = 0, n = dit.depth(); i != n; ++i)
789                 os << " " << dit[i] << "\n";
790         return os;
791 }
792
793
794 ///////////////////////////////////////////////////////
795
796 StableDocIterator::StableDocIterator(DocIterator const & dit) :
797         data_(dit.internalData())
798 {
799         for (size_t i = 0, n = data_.size(); i != n; ++i)
800                 data_[i].inset_ = nullptr;
801 }
802
803
804 DocIterator StableDocIterator::asDocIterator(Buffer * buf) const
805 {
806         DocIterator dit(buf);
807         dit.slices_ = data_;
808         dit.sanitize();
809         return dit;
810 }
811
812
813 ostream & operator<<(ostream & os, StableDocIterator const & dit)
814 {
815         for (size_t i = 0, n = dit.data_.size(); i != n; ++i)
816                 os << " " << dit.data_[i] << "\n";
817         return os;
818 }
819
820
821 bool operator==(StableDocIterator const & dit1, StableDocIterator const & dit2)
822 {
823         return dit1.data_ == dit2.data_;
824 }
825
826
827 } // namespace lyx