]> git.lyx.org Git - lyx.git/blob - src/DocIterator.cpp
Fix embarassing crash caused by debug message
[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 "LaTeXFeatures.h"
24 #include "Paragraph.h"
25 #include "LyXRC.h"
26 #include "Text.h"
27
28 #include "mathed/MathData.h"
29 #include "mathed/InsetMath.h"
30 #include "mathed/InsetMathHull.h"
31
32 #include "insets/InsetTabular.h"
33
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"
40
41 #include <ostream>
42
43 using namespace std;
44 using namespace lyx::support;
45
46 namespace lyx {
47
48
49 DocIterator::DocIterator()
50         : boundary_(false), inset_(0), buffer_(0)
51 {}
52
53
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)
58 {}
59
60
61 DocIterator::DocIterator(Buffer * buf, Inset * inset)
62         : boundary_(false), inset_(inset), buffer_(buf)
63 {}
64
65
66 DocIterator doc_iterator_begin(const Buffer * buf0, const Inset * inset0)
67 {
68         Buffer * buf = const_cast<Buffer *>(buf0);
69         Inset * inset = const_cast<Inset *>(inset0);
70         DocIterator dit(buf, inset ? inset : &buf->inset());
71         dit.forwardPos();
72         return dit;
73 }
74
75
76 DocIterator doc_iterator_end(const Buffer * buf0, const Inset * inset0)
77 {
78         Buffer * buf = const_cast<Buffer *>(buf0);
79         Inset * inset = const_cast<Inset *>(inset0);
80         return DocIterator(buf, inset ? inset : &buf->inset());
81 }
82
83
84 DocIterator DocIterator::clone(Buffer * buffer) const
85 {
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) {
91                 LBUFERR(inset);
92                 dit.push_back(slices_[i]);
93                 dit.top().inset_ = inset;
94                 if (i + 1 != n)
95                         inset = dit.nextInset();
96         }
97         return dit;
98 }
99
100
101 bool DocIterator::inRegexped() const
102 {
103         InsetMath * im = inset().asInsetMath();
104         if (!im)
105                 return false;
106         InsetMathHull * hull = im->asHullInset();
107         return hull && hull->getType() == hullRegexp;
108 }
109
110
111 LyXErr & operator<<(LyXErr & os, DocIterator const & it)
112 {
113         os.stream() << it;
114         return os;
115 }
116
117
118 Inset * DocIterator::nextInset() const
119 {
120         LASSERT(!empty(), return 0);
121         if (pos() == lastpos())
122                 return 0;
123         if (pos() > lastpos()) {
124                 LYXERR0("Should not happen, but it does: pos() = "
125                         << pos() << ", lastpos() = " << lastpos());
126                 return 0;
127         }
128         if (inMathed())
129                 return nextAtom().nucleus();
130         return paragraph().getInset(pos());
131 }
132
133
134 Inset * DocIterator::prevInset() const
135 {
136         LASSERT(!empty(), return 0);
137         if (pos() == 0)
138                 return 0;
139         if (inMathed()) {
140                 if (cell().empty())
141                         // FIXME: this should not happen but it does.
142                         // See bug 3189
143                         // http://www.lyx.org/trac/ticket/3189
144                         return 0;
145                 else
146                         return prevAtom().nucleus();
147         }
148         return paragraph().getInset(pos() - 1);
149 }
150
151
152 Inset * DocIterator::realInset() const
153 {
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();
159         }
160         return &inset();
161 }
162
163
164 MathAtom & DocIterator::prevAtom() const
165 {
166         LASSERT(!empty(), /**/);
167         LASSERT(pos() > 0, /**/);
168         return cell()[pos() - 1];
169 }
170
171
172 MathAtom & DocIterator::nextAtom() const
173 {
174         LASSERT(!empty(), /**/);
175         //lyxerr << "lastpos: " << lastpos() << " next atom:\n" << *this << endl;
176         LASSERT(pos() < lastpos(), /**/);
177         return cell()[pos()];
178 }
179
180
181 Text * DocIterator::text() const
182 {
183         LASSERT(!empty(), return 0);
184         return top().text();
185 }
186
187
188 Paragraph & DocIterator::paragraph() const
189 {
190         if (!inTexted()) {
191                 LYXERR0(*this);
192                 LBUFERR(false);
193         }
194         return top().paragraph();
195 }
196
197
198 Paragraph & DocIterator::innerParagraph() const
199 {
200         LBUFERR(!empty());
201         return innerTextSlice().paragraph();
202 }
203
204
205 FontSpan DocIterator::locateWord(word_location const loc) const
206 {
207         FontSpan f = FontSpan();
208
209         if (!top().text()->empty()) {
210                 f.first = pos();
211                 top().paragraph().locateWord(f.first, f.last, loc);
212         }
213         return f;
214 }
215
216
217 CursorSlice const & DocIterator::innerTextSlice() const
218 {
219         LBUFERR(!empty());
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())
224                         return slices_[i];
225
226         // This case is in principle not possible. We _must_
227         // be inside a Text.
228         LBUFERR(false);
229         // Squash warning
230         static const CursorSlice c;
231         return c;
232 }
233
234
235 docstring DocIterator::paragraphGotoArgument() const
236 {
237         CursorSlice const & s = innerTextSlice();
238         return convert<docstring>(s.paragraph().id()) + ' ' +
239                 convert<docstring>(s.pos());
240 }
241
242
243 DocIterator DocIterator::getInnerText() const
244 {
245         DocIterator texted = *this;
246         while (!texted.inTexted())
247                 texted.pop_back();
248         return texted;
249 }
250
251
252 pit_type DocIterator::lastpit() const
253 {
254         return inMathed() ? 0 : text()->paragraphs().size() - 1;
255 }
256
257
258 pos_type DocIterator::lastpos() const
259 {
260         return inMathed() ? cell().size() : paragraph().size();
261 }
262
263
264 DocIterator::idx_type DocIterator::lastidx() const
265 {
266         return top().lastidx();
267 }
268
269
270 size_t DocIterator::nargs() const
271 {
272         // assume 1x1 grid for main text
273         return top().nargs();
274 }
275
276
277 size_t DocIterator::ncols() const
278 {
279         // assume 1x1 grid for main text
280         return top().ncols();
281 }
282
283
284 size_t DocIterator::nrows() const
285 {
286         // assume 1x1 grid for main text
287         return top().nrows();
288 }
289
290
291 DocIterator::row_type DocIterator::row() const
292 {
293         return top().row();
294 }
295
296
297 DocIterator::col_type DocIterator::col() const
298 {
299         return top().col();
300 }
301
302
303 MathData & DocIterator::cell() const
304 {
305 //      LASSERT(inMathed(), /**/);
306         return top().cell();
307 }
308
309
310 Text * DocIterator::innerText() const
311 {
312         LASSERT(!empty(), return 0);
313         return innerTextSlice().text();
314 }
315
316
317 Inset * DocIterator::innerInsetOfType(int code) const
318 {
319         for (int i = depth() - 1; i >= 0; --i)
320                 if (slices_[i].inset_->lyxCode() == code)
321                         return slices_[i].inset_;
322         return 0;
323 }
324
325
326 bool DocIterator::posBackward()
327 {
328         if (pos() == 0)
329                 return false;
330         --pos();
331         return true;
332 }
333
334
335 bool DocIterator::posForward()
336 {
337         if (pos() == lastpos())
338                 return false;
339         ++pos();
340         return true;
341 }
342
343
344 // This duplicates code above, but is in the critical path.
345 // So please think twice before adding stuff
346 void DocIterator::forwardPos()
347 {
348         // this dog bites his tail
349         if (empty()) {
350                 push_back(CursorSlice(*inset_));
351                 return;
352         }
353
354         CursorSlice & tip = top();
355         //lyxerr << "XXX\n" << *this << endl;
356
357         // not at cell/paragraph end?
358         if (tip.pos() != tip.lastpos()) {
359                 // move into an inset to the right if possible
360                 Inset * n = 0;
361                 if (inMathed())
362                         n = (tip.cell().begin() + tip.pos())->nucleus();
363                 else
364                         n = paragraph().getInset(tip.pos());
365                 if (n && n->isActive()) {
366                         //lyxerr << "... descend" << endl;
367                         push_back(CursorSlice(*n));
368                         return;
369                 }
370         }
371
372         // jump to the next cell/paragraph if possible
373         if (!tip.at_end()) {
374                 tip.forwardPos();
375                 return;
376         }
377
378         // otherwise leave inset and jump over inset as a whole
379         pop_back();
380         // 'tip' is invalid now...
381         if (!empty())
382                 ++top().pos();
383 }
384
385
386 void DocIterator::forwardPosIgnoreCollapsed()
387 {
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()) {
393                 ++top().pos();
394                 return;
395         }
396         forwardPos();
397 }
398
399
400 void DocIterator::forwardPar()
401 {
402         forwardPos();
403
404         while (!empty() && (!inTexted() || pos() != 0)) {
405                 if (inTexted()) {
406                         pos_type const lastp = lastpos();
407                         Paragraph const & par = paragraph();
408                         pos_type & pos = top().pos();
409                         if (par.insetList().empty())
410                                 pos = lastp;
411                         else
412                                 while (pos < lastp && !par.isInset(pos))
413                                         ++pos;
414                 }
415                 forwardPos();
416         }
417 }
418
419
420 void DocIterator::forwardChar()
421 {
422         forwardPos();
423         while (!empty() && pos() == lastpos())
424                 forwardPos();
425 }
426
427
428 void DocIterator::forwardInset()
429 {
430         forwardPos();
431
432         while (!empty() && !nextInset()) {
433                 if (inTexted()) {
434                         pos_type const lastp = lastpos();
435                         Paragraph const & par = paragraph();
436                         pos_type & pos = top().pos();
437                         while (pos < lastp && !par.isInset(pos))
438                                 ++pos;
439                         if (pos < lastp)
440                                 break;
441                 }
442                 forwardPos();
443         }
444 }
445
446
447 void DocIterator::backwardChar()
448 {
449         backwardPos();
450         while (!empty() && pos() == lastpos())
451                 backwardPos();
452 }
453
454
455 void DocIterator::backwardPos()
456 {
457         //this dog bites his tail
458         if (empty()) {
459                 push_back(CursorSlice(*inset_));
460                 top().idx() = lastidx();
461                 top().pit() = lastpit();
462                 top().pos() = lastpos();
463                 return;
464         }
465
466         // at inset beginning?
467         if (top().at_begin()) {
468                 pop_back();
469                 return;
470         }
471
472         top().backwardPos();
473
474         // entered another cell/paragraph from the right?
475         if (top().pos() == top().lastpos())
476                 return;
477
478         // move into an inset to the left if possible
479         Inset * n = 0;
480         if (inMathed())
481                 n = (top().cell().begin() + top().pos())->nucleus();
482         else
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();
489         }
490 }
491
492
493 #if 0
494 // works, but currently not needed
495 void DocIterator::backwardInset()
496 {
497         backwardPos();
498
499         while (!empty() && !nextInset()) {
500                 if (inTexted()) {
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)))
505                                 --pos;
506                         if (pos > 0)
507                                 break;
508                 }
509                 backwardPos();
510         }
511 }
512 #endif
513
514
515 bool DocIterator::hasPart(DocIterator const & it) const
516 {
517         // it can't be a part if it is larger
518         if (it.depth() > depth())
519                 return false;
520
521         // as inset adresses are the 'last' level
522         return &it.top().inset() == &slices_[it.depth() - 1].inset();
523 }
524
525
526 bool DocIterator::allowSpellCheck() const
527 {
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())
533                         return false;
534         }
535         return true;
536 }
537
538
539 void DocIterator::updateInsets(Inset * inset)
540 {
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();
545         slices_.resize(0);
546         for (size_t i = 0 ; i < n; ++i) {
547                 LBUFERR(inset);
548                 push_back(dit[i]);
549                 top().inset_ = inset;
550                 if (i + 1 != n)
551                         inset = nextInset();
552         }
553         //lyxerr << "converted:\n" << *this << endl;
554 }
555
556
557 bool DocIterator::fixIfBroken()
558 {
559         if (empty())
560                 return false;
561
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();
566         size_t i = 0;
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
572                         --i;
573                         LYXERR(Debug::DEBUG, "fixIfBroken(): inset changed");
574                         break;
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");
580                         break;
581                 } else if (cs.pit() > cs.lastpit()) {
582                         cs.pit() = cs.lastpit();
583                         cs.pos() = cs.lastpos();
584                         LYXERR(Debug::DEBUG, "fixIfBroken(): pit fixed");
585                         break;
586                 } else if (cs.pos() > cs.lastpos()) {
587                         cs.pos() = cs.lastpos();
588                         LYXERR(Debug::DEBUG, "fixIfBroken(): pos fixed");
589                         break;
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()))
595                                 inset = csInset;
596                         else {
597                                 // there are slices left, so there must be another inset
598                                 break;
599                         }
600                 }
601         }
602
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
605         if (i < n) {
606                 LYXERR(Debug::DEBUG, "fixIfBroken(): cursor chopped at " << i);
607                 resize(i + 1);
608                 return true;
609         } else
610                 return false;
611 }
612
613
614 void DocIterator::sanitize()
615 {
616         // keep a copy of the slices
617         vector<CursorSlice> const sl = slices_;
618         slices_.clear();
619         if (buffer_)
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) {
624                 if (inset == 0) {
625                         // FIXME
626                         LYXERR0("Null inset on cursor stack.");
627                         fixIfBroken();
628                         break;
629                 }
630                 if (!inset->isActive()) {
631                         LYXERR0("Inset found on cursor stack is not active.");
632                         fixIfBroken();
633                         break;
634                 }
635                 push_back(sl[i]);
636                 top().inset_ = inset;
637                 if (fixIfBroken())
638                         break;
639                 if (i + 1 != n)
640                         inset = nextInset();
641         }
642 }
643
644
645 int DocIterator::find(MathData const & cell) const
646 {
647         for (size_t l = 0; l != slices_.size(); ++l) {
648                 if (slices_[l].asInsetMath() && &slices_[l].cell() == &cell)
649                         return l;
650         }
651         return -1;
652 }
653
654
655 int DocIterator::find(Inset const * inset) const
656 {
657         for (size_t l = 0; l != slices_.size(); ++l) {
658                 if (&slices_[l].inset() == inset)
659                         return l;
660         }
661         return -1;
662 }
663
664
665 void DocIterator::cutOff(int above, vector<CursorSlice> & cut)
666 {
667         cut = vector<CursorSlice>(slices_.begin() + above + 1, slices_.end());
668         slices_.resize(above + 1);
669 }
670
671
672 void DocIterator::cutOff(int above)
673 {
674         slices_.resize(above + 1);
675 }
676
677
678 void DocIterator::append(vector<CursorSlice> const & x)
679 {
680         slices_.insert(slices_.end(), x.begin(), x.end());
681 }
682
683
684 void DocIterator::append(DocIterator::idx_type idx, pos_type pos)
685 {
686         slices_.push_back(CursorSlice());
687         top().idx() = idx;
688         top().pos() = pos;
689 }
690
691
692 Encoding const * DocIterator::getEncoding() const
693 {
694         if (empty())
695                 return 0;
696
697         BufferParams const & bp = buffer()->params();
698         if (bp.useNonTeXFonts)
699                 return encodings.fromLyXName("utf8-plain");
700
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 =
714                 (customenc
715                  && (lang->encoding()->package() != Encoding::CJK || !cjk_non_utf8))
716                 ? &bp.encoding() : lang->encoding();
717
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);
731                 }
732                 // Fall back to buffer encoding if no outer lang was found.
733                 return inset().forcedEncoding(enc, &bp.encoding());
734         }
735
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 =
748                                         (customenc
749                                          && (olang->encoding()->package() != Encoding::CJK || !cjk_non_utf8))
750                                         ? &bp.encoding() : olang->encoding();
751                         if (olang->encoding()->name() != "inherit")
752                                 return oenc;
753                 }
754         }
755
756         return enc;
757 }
758
759
760 ostream & operator<<(ostream & os, DocIterator const & dit)
761 {
762         for (size_t i = 0, n = dit.depth(); i != n; ++i)
763                 os << " " << dit[i] << "\n";
764         return os;
765 }
766
767
768 ///////////////////////////////////////////////////////
769
770 StableDocIterator::StableDocIterator(DocIterator const & dit) :
771         data_(dit.internalData())
772 {
773         for (size_t i = 0, n = data_.size(); i != n; ++i)
774                 data_[i].inset_ = 0;
775 }
776
777
778 DocIterator StableDocIterator::asDocIterator(Buffer * buf) const
779 {
780         DocIterator dit(buf);
781         dit.slices_ = data_;
782         dit.sanitize();
783         return dit;
784 }
785
786
787 ostream & operator<<(ostream & os, StableDocIterator const & dit)
788 {
789         for (size_t i = 0, n = dit.data_.size(); i != n; ++i)
790                 os << " " << dit.data_[i] << "\n";
791         return os;
792 }
793
794
795 bool operator==(StableDocIterator const & dit1, StableDocIterator const & dit2)
796 {
797         return dit1.data_ == dit2.data_;
798 }
799
800
801 } // namespace lyx