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