]> git.lyx.org Git - lyx.git/blob - src/cursor.C
make sure the 'setStatus(Collapsed)' crash won't occur otherwise
[lyx.git] / src / cursor.C
1 /**
2  * \file cursor.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Alfredo Braunstein
8  * \author André Pönitz
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "BufferView.h"
16 #include "buffer.h"
17 #include "cursor.h"
18 #include "coordcache.h"
19 #include "CutAndPaste.h"
20 #include "debug.h"
21 #include "dispatchresult.h"
22 #include "encoding.h"
23 #include "funcrequest.h"
24 #include "language.h"
25 #include "lfuns.h"
26 #include "lyxfont.h"
27 #include "lyxfunc.h" // only for setMessage()
28 #include "lyxrc.h"
29 #include "lyxrow.h"
30 #include "lyxtext.h"
31 #include "paragraph.h"
32 #include "paragraph_funcs.h"
33 #include "pariterator.h"
34
35 #include "insets/updatableinset.h"
36 #include "insets/insettabular.h"
37 #include "insets/insettext.h"
38
39 #include "mathed/math_data.h"
40 #include "mathed/math_inset.h"
41 #include "mathed/math_macrotable.h"
42
43 #include "support/limited_stack.h"
44
45 #include "frontends/LyXView.h"
46 #include "frontends/font_metrics.h"
47
48 #include <boost/assert.hpp>
49 #include <boost/bind.hpp>
50 #include <boost/current_function.hpp>
51
52 #include <sstream>
53 #include <limits>
54
55 using lyx::pit_type;
56
57 using std::string;
58 using std::vector;
59 using std::endl;
60 #ifndef CXX_GLOBAL_CSTD
61 using std::isalpha;
62 #endif
63 using std::min;
64 using std::swap;
65
66 namespace {
67
68         bool
69         positionable(DocIterator const & cursor, DocIterator const & anchor)
70         {
71                 // avoid deeper nested insets when selecting
72                 if (cursor.depth() > anchor.depth())
73                         return false;
74
75                 // anchor might be deeper, should have same path then
76                 for (size_t i = 0; i < cursor.depth(); ++i)
77                         if (&cursor[i].inset() != &anchor[i].inset())
78                                 return false;
79
80                 // position should be ok.
81                 return true;
82         }
83
84
85         // Find position closest to (x, y) in cell given by iter.
86         // Used only in mathed
87         DocIterator bruteFind2(LCursor const & c, int x, int y)
88         {
89                 double best_dist = std::numeric_limits<double>::max();
90
91                 DocIterator result;
92
93                 DocIterator it = c;
94                 it.top().pos() = 0;
95                 DocIterator et = c;
96                 et.top().pos() = et.top().asMathInset()->cell(et.top().idx()).size();
97                 for (int i = 0; ; ++i) {
98                         int xo;
99                         int yo;
100                         LCursor cur = c;
101                         cur.setCursor(it);
102                         cur.inset().getCursorPos(cur.top(), xo, yo);
103                         double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
104                         // '<=' in order to take the last possible position
105                         // this is important for clicking behind \sum in e.g. '\sum_i a'
106                         lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
107                                 << " best: " << best_dist << endl;
108                         if (d <= best_dist) {
109                                 best_dist = d;
110                                 result = it;
111                         }
112                         if (it == et)
113                                 break;
114                         it.forwardPos();
115                 }
116                 return result;
117         }
118
119
120         /// moves position closest to (x, y) in given box
121         bool bruteFind(LCursor & cursor,
122                 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
123         {
124                 BOOST_ASSERT(!cursor.empty());
125                 CursorSlice bottom = cursor[0];
126
127                 DocIterator it = doc_iterator_begin(bottom.inset());
128                 DocIterator const et = doc_iterator_end(bottom.inset());
129
130                 double best_dist = std::numeric_limits<double>::max();;
131                 DocIterator best_cursor = et;
132
133                 for ( ; it != et; it.forwardPos()) {
134                         // avoid invalid nesting when selecting
135                         if (bv_funcs::status(&cursor.bv(), it) == bv_funcs::CUR_INSIDE
136                             && (!cursor.selection() || positionable(it, cursor.anchor_))) {
137                                 Point p = bv_funcs::getPos(it);
138                                 int xo = p.x_;
139                                 int yo = p.y_;
140                                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
141                                         double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
142                                         //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
143                                         // '<=' in order to take the last possible position
144                                         // this is important for clicking behind \sum in e.g. '\sum_i a'
145                                         if (d <= best_dist) {
146                                                 //lyxerr << "*" << endl;
147                                                 best_dist   = d;
148                                                 best_cursor = it;
149                                         }
150                                 }
151                         }
152                 }
153
154                 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
155                 if (best_cursor != et) {
156                         cursor.setCursor(best_cursor);
157                         return true;
158                 }
159
160                 return false;
161         }
162
163 } // namespace anon
164
165
166 // be careful: this is called from the bv's constructor, too, so
167 // bv functions are not yet available!
168 LCursor::LCursor(BufferView & bv)
169         : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
170           selection_(false), mark_(false)
171 {}
172
173
174 void LCursor::reset(InsetBase & inset)
175 {
176         clear();
177         push_back(CursorSlice(inset));
178         anchor_ = DocIterator(inset);
179         clearTargetX();
180         selection_ = false;
181         mark_ = false;
182 }
183
184
185 // this (intentionally) does neither touch anchor nor selection status
186 void LCursor::setCursor(DocIterator const & cur)
187 {
188         DocIterator::operator=(cur);
189 }
190
191
192 void LCursor::dispatch(FuncRequest const & cmd0)
193 {
194         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
195                              << " cmd: " << cmd0 << '\n'
196                              << *this << endl;
197         if (empty())
198                 return;
199
200         fixIfBroken();
201         FuncRequest cmd = cmd0;
202         LCursor safe = *this;
203
204         for (; depth(); pop()) {
205                 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
206                         << cmd0 << endl << *this << endl;
207                 BOOST_ASSERT(pos() <= lastpos());
208                 BOOST_ASSERT(idx() <= lastidx());
209                 BOOST_ASSERT(pit() <= lastpit());
210
211                 // The common case is 'LFUN handled, need update', so make the
212                 // LFUN handler's life easier by assuming this as default value.
213                 // The handler can reset the update and val flags if necessary.
214                 disp_.update(true);
215                 disp_.dispatched(true);
216                 inset().dispatch(*this, cmd);
217                 if (disp_.dispatched())
218                         break;
219         }
220         // it completely to get a 'bomb early' behaviour in case this
221         // object will be used again.
222         if (!disp_.dispatched()) {
223                 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
224                 operator=(safe);
225                 disp_.dispatched(false);
226         }
227 }
228
229
230 DispatchResult LCursor::result() const
231 {
232         return disp_;
233 }
234
235
236 BufferView & LCursor::bv() const
237 {
238         BOOST_ASSERT(bv_);
239         return *bv_;
240 }
241
242
243 Buffer & LCursor::buffer() const
244 {
245         BOOST_ASSERT(bv_);
246         BOOST_ASSERT(bv_->buffer());
247         return *bv_->buffer();
248 }
249
250
251 void LCursor::pop()
252 {
253         BOOST_ASSERT(depth() >= 1);
254         pop_back();
255 }
256
257
258 void LCursor::push(InsetBase & p)
259 {
260         push_back(CursorSlice(p));
261 }
262
263
264 void LCursor::pushLeft(InsetBase & p)
265 {
266         BOOST_ASSERT(!empty());
267         //lyxerr << "Entering inset " << t << " left" << endl;
268         push(p);
269         p.idxFirst(*this);
270 }
271
272
273 bool LCursor::popLeft()
274 {
275         BOOST_ASSERT(!empty());
276         //lyxerr << "Leaving inset to the left" << endl;
277         inset().notifyCursorLeaves(*this);
278         if (depth() == 1)
279                 return false;
280         pop();
281         return true;
282 }
283
284
285 bool LCursor::popRight()
286 {
287         BOOST_ASSERT(!empty());
288         //lyxerr << "Leaving inset to the right" << endl;
289         inset().notifyCursorLeaves(*this);
290         if (depth() == 1)
291                 return false;
292         pop();
293         ++pos();
294         return true;
295 }
296
297
298 int LCursor::currentMode()
299 {
300         BOOST_ASSERT(!empty());
301         for (int i = depth() - 1; i >= 0; --i) {
302                 int res = operator[](i).inset().currentMode();
303                 if (res != InsetBase::UNDECIDED_MODE)
304                         return res;
305         }
306         return InsetBase::TEXT_MODE;
307 }
308
309
310 void LCursor::getPos(int & x, int & y) const
311 {
312         Point p = bv_funcs::getPos(*this);
313         x = p.x_;
314         y = p.y_;
315 }
316
317
318 void LCursor::paste(string const & data)
319 {
320         dispatch(FuncRequest(LFUN_PASTE, data));
321 }
322
323
324 void LCursor::resetAnchor()
325 {
326         anchor_ = *this;
327 }
328
329
330
331 bool LCursor::posLeft()
332 {
333         if (pos() == 0)
334                 return false;
335         --pos();
336         return true;
337 }
338
339
340 bool LCursor::posRight()
341 {
342         if (pos() == lastpos())
343                 return false;
344         ++pos();
345         return true;
346 }
347
348
349 CursorSlice LCursor::anchor() const
350 {
351         BOOST_ASSERT(anchor_.depth() >= depth());
352         CursorSlice normal = anchor_[depth() - 1];
353         if (depth() < anchor_.depth() && top() <= normal) {
354                 // anchor is behind cursor -> move anchor behind the inset
355                 ++normal.pos();
356         }
357         return normal;
358 }
359
360
361 CursorSlice LCursor::selBegin() const
362 {
363         if (!selection())
364                 return top();
365         return anchor() < top() ? anchor() : top();
366 }
367
368
369 CursorSlice LCursor::selEnd() const
370 {
371         if (!selection())
372                 return top();
373         return anchor() > top() ? anchor() : top();
374 }
375
376
377 DocIterator LCursor::selectionBegin() const
378 {
379         if (!selection())
380                 return *this;
381         return anchor() < top() ? anchor_ : *this;
382 }
383
384
385 DocIterator LCursor::selectionEnd() const
386 {
387         if (!selection())
388                 return *this;
389         return anchor() > top() ? anchor_ : *this;
390 }
391
392
393 void LCursor::setSelection()
394 {
395         selection() = true;
396         // a selection with no contents is not a selection
397 #ifdef WITH_WARNINGS
398 #warning doesnt look ok
399 #endif
400         if (pit() == anchor().pit() && pos() == anchor().pos())
401                 selection() = false;
402 }
403
404
405 void LCursor::setSelection(DocIterator const & where, size_t n)
406 {
407         setCursor(where);
408         selection() = true;
409         anchor_ = where;
410         pos() += n;
411 }
412
413
414 void LCursor::clearSelection()
415 {
416         selection() = false;
417         mark() = false;
418         resetAnchor();
419         bv().unsetXSel();
420 }
421
422
423 int & LCursor::x_target()
424 {
425         return x_target_;
426 }
427
428
429 int LCursor::x_target() const
430 {
431         return x_target_;
432 }
433
434
435 void LCursor::clearTargetX()
436 {
437         x_target_ = -1;
438 }
439
440
441
442 void LCursor::info(std::ostream & os) const
443 {
444         for (int i = 1, n = depth(); i < n; ++i) {
445                 operator[](i).inset().infoize(os);
446                 os << "  ";
447         }
448         if (pos() != 0)
449                 prevInset()->infoize2(os);
450         // overwite old message
451         os << "                    ";
452 }
453
454
455 void LCursor::selHandle(bool sel)
456 {
457         //lyxerr << "LCursor::selHandle" << endl;
458         if (sel == selection())
459                 return;
460
461         resetAnchor();
462         selection() = sel;
463 }
464
465
466 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
467 {
468         os << "\n cursor:                                | anchor:\n";
469         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
470                 os << " " << cur[i] << " | ";
471                 if (i < cur.anchor_.depth())
472                         os << cur.anchor_[i];
473                 else
474                         os << "-------------------------------";
475                 os << "\n";
476         }
477         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
478                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
479         }
480         os << " selection: " << cur.selection_
481            << " x_target: " << cur.x_target_ << endl;
482         return os;
483 }
484
485
486
487
488 ///////////////////////////////////////////////////////////////////
489 //
490 // The part below is the non-integrated rest of the original math
491 // cursor. This should be either generalized for texted or moved
492 // back to mathed (in most cases to MathNestInset).
493 //
494 ///////////////////////////////////////////////////////////////////
495
496 #include "mathed/math_charinset.h"
497 #include "mathed/math_factory.h"
498 #include "mathed/math_gridinset.h"
499 #include "mathed/math_macroarg.h"
500 #include "mathed/math_mathmlstream.h"
501 #include "mathed/math_scriptinset.h"
502 #include "mathed/math_support.h"
503 #include "mathed/math_unknowninset.h"
504
505 //#define FILEDEBUG 1
506
507
508 bool LCursor::isInside(InsetBase const * p)
509 {
510         for (size_t i = 0; i != depth(); ++i)
511                 if (&operator[](i).inset() == p)
512                         return true;
513         return false;
514 }
515
516
517 void LCursor::leaveInset(InsetBase const & inset)
518 {
519         for (size_t i = 0; i != depth(); ++i) {
520                 if (&operator[](i).inset() == &inset) {
521                         resize(i);
522                         return;
523                 }
524         }
525 }
526
527
528 bool LCursor::openable(MathAtom const & t) const
529 {
530         if (!t->isActive())
531                 return false;
532
533         if (t->lock())
534                 return false;
535
536         if (!selection())
537                 return true;
538
539         // we can't move into anything new during selection
540         if (depth() >= anchor_.depth())
541                 return false;
542         if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
543                 return false;
544
545         return true;
546 }
547
548
549 void LCursor::setScreenPos(int x, int y)
550 {
551         x_target() = x;
552         bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
553 }
554
555
556
557 void LCursor::plainErase()
558 {
559         cell().erase(pos());
560 }
561
562
563 void LCursor::markInsert()
564 {
565         insert(char(0));
566 }
567
568
569 void LCursor::markErase()
570 {
571         cell().erase(pos());
572 }
573
574
575 void LCursor::plainInsert(MathAtom const & t)
576 {
577         cell().insert(pos(), t);
578         ++pos();
579 }
580
581
582 void LCursor::insert(string const & str)
583 {
584         for_each(str.begin(), str.end(),
585                  boost::bind(static_cast<void(LCursor::*)(char)>
586                              (&LCursor::insert), this, _1));
587 }
588
589
590 void LCursor::insert(char c)
591 {
592         //lyxerr << "LCursor::insert char '" << c << "'" << endl;
593         BOOST_ASSERT(!empty());
594         if (inMathed()) {
595                 lyx::cap::selClearOrDel(*this);
596                 insert(new MathCharInset(c));
597         } else {
598                 text()->insertChar(*this, c);
599         }
600 }
601
602
603 void LCursor::insert(MathAtom const & t)
604 {
605         //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
606         macroModeClose();
607         lyx::cap::selClearOrDel(*this);
608         plainInsert(t);
609 }
610
611
612 void LCursor::insert(InsetBase * inset)
613 {
614         if (inMathed())
615                 insert(MathAtom(inset));
616         else
617                 text()->insertInset(*this, inset);
618 }
619
620
621 void LCursor::niceInsert(string const & t)
622 {
623         MathArray ar;
624         asArray(t, ar);
625         if (ar.size() == 1)
626                 niceInsert(ar[0]);
627         else
628                 insert(ar);
629 }
630
631
632 void LCursor::niceInsert(MathAtom const & t)
633 {
634         macroModeClose();
635         string const safe = lyx::cap::grabAndEraseSelection(*this);
636         plainInsert(t);
637         // enter the new inset and move the contents of the selection if possible
638         if (t->isActive()) {
639                 posLeft();
640                 // be careful here: don't use 'pushLeft(t)' as this we need to
641                 // push the clone, not the original
642                 pushLeft(*nextInset());
643                 paste(safe);
644         }
645 }
646
647
648 void LCursor::insert(MathArray const & ar)
649 {
650         macroModeClose();
651         if (selection())
652                 lyx::cap::eraseSelection(*this);
653         cell().insert(pos(), ar);
654         pos() += ar.size();
655 }
656
657
658 bool LCursor::backspace()
659 {
660         autocorrect() = false;
661
662         if (selection()) {
663                 lyx::cap::selDel(*this);
664                 return true;
665         }
666
667         if (pos() == 0) {
668                 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
669                         return false;
670                 pullArg();
671                 return true;
672         }
673
674         if (inMacroMode()) {
675                 MathUnknownInset * p = activeMacro();
676                 if (p->name().size() > 1) {
677                         p->setName(p->name().substr(0, p->name().size() - 1));
678                         return true;
679                 }
680         }
681
682         if (pos() != 0 && prevAtom()->nargs() > 0) {
683                 // let's require two backspaces for 'big stuff' and
684                 // highlight on the first
685                 resetAnchor();
686                 selection() = true;
687                 --pos();
688         } else {
689                 --pos();
690                 plainErase();
691         }
692         return true;
693 }
694
695
696 bool LCursor::erase()
697 {
698         autocorrect() = false;
699         if (inMacroMode())
700                 return true;
701
702         if (selection()) {
703                 lyx::cap::selDel(*this);
704                 return true;
705         }
706
707         // delete empty cells if possible
708         if (pos() == lastpos() && inset().idxDelete(idx()))
709                 return true;
710
711         // special behaviour when in last position of cell
712         if (pos() == lastpos()) {
713                 bool one_cell = inset().nargs() == 1;
714                 if (one_cell && depth() == 1 && lastpos() == 0)
715                         return false;
716                 // remove markup
717                 if (one_cell)
718                         pullArg();
719                 else
720                         inset().idxGlue(idx());
721                 return true;
722         }
723
724         // 'clever' UI hack: only erase large items if previously slected
725         if (pos() != lastpos() && inset().nargs() > 0) {
726                 resetAnchor();
727                 selection() = true;
728                 ++pos();
729         } else {
730                 plainErase();
731         }
732
733         return true;
734 }
735
736
737 bool LCursor::up()
738 {
739         macroModeClose();
740         DocIterator save = *this;
741         if (goUpDown(true))
742                 return true;
743         setCursor(save);
744         autocorrect() = false;
745         return selection();
746 }
747
748
749 bool LCursor::down()
750 {
751         macroModeClose();
752         DocIterator save = *this;
753         if (goUpDown(false))
754                 return true;
755         setCursor(save);
756         autocorrect() = false;
757         return selection();
758 }
759
760
761 void LCursor::macroModeClose()
762 {
763         if (!inMacroMode())
764                 return;
765         MathUnknownInset * p = activeMacro();
766         p->finalize();
767         string const s = p->name();
768         --pos();
769         cell().erase(pos());
770
771         // do nothing if the macro name is empty
772         if (s == "\\")
773                 return;
774
775         string const name = s.substr(1);
776
777         // prevent entering of recursive macros
778         // FIXME: this is only a weak attempt... only prevents immediate
779         // recursion
780         InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
781         if (macro && macro->getInsetName() == name)
782                 lyxerr << "can't enter recursive macro" << endl;
783
784         plainInsert(createMathInset(name));
785 }
786
787
788 string LCursor::macroName()
789 {
790         return inMacroMode() ? activeMacro()->name() : string();
791 }
792
793
794 void LCursor::handleNest(MathAtom const & a, int c)
795 {
796         //lyxerr << "LCursor::handleNest: " << c << endl;
797         MathAtom t = a;
798         asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
799         insert(t);
800         posLeft();
801         pushLeft(*nextInset());
802 }
803
804
805 int LCursor::targetX() const
806 {
807         if (x_target() != -1)
808                 return x_target();
809         int x = 0;
810         int y = 0;
811         getPos(x, y);
812         return x;
813 }
814
815
816 void LCursor::setTargetX()
817 {
818         // For now this is good enough. A better solution would be to
819         // avoid this rebreak by setting cursorX only after drawing
820         bottom().text()->redoParagraph(bottom().pit());
821         int x;
822         int y;
823         getPos(x, y);
824         x_target_ = x;
825 }
826
827
828 bool LCursor::inMacroMode() const
829 {
830         if (pos() == 0)
831                 return false;
832         MathUnknownInset const * p = prevAtom()->asUnknownInset();
833         return p && !p->final();
834 }
835
836
837 MathUnknownInset * LCursor::activeMacro()
838 {
839         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
840 }
841
842
843 void LCursor::pullArg()
844 {
845 #ifdef WITH_WARNINGS
846 #warning Look here
847 #endif
848         MathArray ar = cell();
849         if (popLeft() && inMathed()) {
850                 plainErase();
851                 cell().insert(pos(), ar);
852                 resetAnchor();
853         } else {
854                 //formula()->mutateToText();
855         }
856 }
857
858
859 void LCursor::touch()
860 {
861 #ifdef WITH_WARNINGS
862 #warning look here
863 #endif
864 #if 0
865         DocIterator::const_iterator it = begin();
866         DocIterator::const_iterator et = end();
867         for ( ; it != et; ++it)
868                 it->cell().touch();
869 #endif
870 }
871
872
873 void LCursor::normalize()
874 {
875         if (idx() >= nargs()) {
876                 lyxerr << "this should not really happen - 1: "
877                        << idx() << ' ' << nargs()
878                        << " in: " << &inset() << endl;
879         }
880         idx() = min(idx(), lastidx());
881
882         if (pos() > lastpos()) {
883                 lyxerr << "this should not really happen - 2: "
884                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
885                        << " in atom: '";
886                 WriteStream wi(lyxerr, false, true);
887                 inset().asMathInset()->write(wi);
888                 lyxerr << endl;
889         }
890         pos() = min(pos(), lastpos());
891 }
892
893
894 bool LCursor::goUpDown(bool up)
895 {
896         // Be warned: The 'logic' implemented in this function is highly
897         // fragile. A distance of one pixel or a '<' vs '<=' _really
898         // matters. So fiddle around with it only if you think you know
899         // what you are doing!
900
901         int xo = 0;
902         int yo = 0;
903         getPos(xo, yo);
904
905         // check if we had something else in mind, if not, this is the future goal
906         if (x_target() == -1)
907                 x_target() = xo;
908         else
909                 xo = x_target();
910
911         // try neigbouring script insets
912         if (!selection()) {
913                 // try left
914                 if (pos() != 0) {
915                         MathScriptInset const * p = prevAtom()->asScriptInset();
916                         if (p && p->has(up)) {
917                                 --pos();
918                                 push(inset());
919                                 idx() = up; // the superscript has index 1
920                                 pos() = lastpos();
921                                 //lyxerr << "updown: handled by scriptinset to the left" << endl;
922                                 return true;
923                         }
924                 }
925
926                 // try right
927                 if (pos() != lastpos()) {
928                         MathScriptInset const * p = nextAtom()->asScriptInset();
929                         if (p && p->has(up)) {
930                                 push(inset());
931                                 idx() = up;
932                                 pos() = 0;
933                                 //lyxerr << "updown: handled by scriptinset to the right" << endl;
934                                 return true;
935                         }
936                 }
937         }
938
939         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
940         //if (up)
941         //      yhigh = yo - 4;
942         //else
943         //      ylow = yo + 4;
944         //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
945         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
946         //      return true;
947         //}
948
949         // try to find an inset that knows better then we
950         while (true) {
951                 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
952                 // ask inset first
953                 if (inset().idxUpDown(*this, up)) {
954                         // try to find best position within this inset
955                         if (!selection())
956                                 setCursor(bruteFind2(*this, xo, yo));
957                         return true;
958                 }
959
960                 // no such inset found, just take something "above"
961                 //lyxerr << "updown: handled by strange case" << endl;
962                 if (!popLeft()) {
963                         int ylow  = up ? 0 : yo + 1;
964                         int yhigh = up ? yo - 1 : bv().workHeight();
965                         return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
966                 }
967
968                 // any improvement so far?
969                 int xnew;
970                 int ynew;
971                 getPos(xnew, ynew);
972                 if (up ? ynew < yo : ynew > yo)
973                         return true;
974         }
975
976         // we should not come here.
977         BOOST_ASSERT(false);
978 }
979
980
981 void LCursor::handleFont(string const & font)
982 {
983         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
984         string safe;
985         if (selection()) {
986                 macroModeClose();
987                 safe = lyx::cap::grabAndEraseSelection(*this);
988         }
989
990         if (lastpos() != 0) {
991                 // something left in the cell
992                 if (pos() == 0) {
993                         // cursor in first position
994                         popLeft();
995                 } else if (pos() == lastpos()) {
996                         // cursor in last position
997                         popRight();
998                 } else {
999                         // cursor in between. split cell
1000                         MathArray::iterator bt = cell().begin();
1001                         MathAtom at = createMathInset(font);
1002                         at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1003                         cell().erase(bt, bt + pos());
1004                         popLeft();
1005                         plainInsert(at);
1006                 }
1007         } else {
1008                 // nothing left in the cell
1009                 pullArg();
1010                 plainErase();
1011         }
1012         insert(safe);
1013 }
1014
1015
1016 void LCursor::message(string const & msg) const
1017 {
1018         bv().owner()->getLyXFunc().setMessage(msg);
1019 }
1020
1021
1022 void LCursor::errorMessage(string const & msg) const
1023 {
1024         bv().owner()->getLyXFunc().setErrorMessage(msg);
1025 }
1026
1027
1028 string LCursor::selectionAsString(bool label) const
1029 {
1030         if (!selection())
1031                 return string();
1032
1033         if (inTexted()) {
1034                 Buffer const & buffer = *bv().buffer();
1035                 ParagraphList & pars = text()->paragraphs();
1036
1037                 // should be const ...
1038                 pit_type startpit = selBegin().pit();
1039                 pit_type endpit = selEnd().pit();
1040                 size_t const startpos = selBegin().pos();
1041                 size_t const endpos = selEnd().pos();
1042
1043                 if (startpit == endpit)
1044                         return pars[startpit].asString(buffer, startpos, endpos, label);
1045
1046                 // First paragraph in selection
1047                 string result = pars[startpit].
1048                         asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1049
1050                 // The paragraphs in between (if any)
1051                 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1052                         Paragraph & par = pars[pit];
1053                         result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1054                 }
1055
1056                 // Last paragraph in selection
1057                 result += pars[endpit].asString(buffer, 0, endpos, label);
1058
1059                 return result;
1060         }
1061
1062 #ifdef WITH_WARNINGS
1063 #warning and mathed?
1064 #endif
1065         return string();
1066 }
1067
1068
1069 string LCursor::currentState()
1070 {
1071         if (inMathed()) {
1072                 std::ostringstream os;
1073                 info(os);
1074                 return os.str();
1075         }
1076
1077         if (inTexted())
1078                 return text()->currentState(*this);
1079
1080         return string();
1081 }
1082
1083
1084 string LCursor::getPossibleLabel()
1085 {
1086         return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1087 }
1088
1089
1090 Encoding const * LCursor::getEncoding() const
1091 {
1092         if (empty())
1093                 return 0;
1094         if (!bv().buffer())
1095                 return 0;
1096         int s = 0;
1097         // go up until first non-0 text is hit
1098         // (innermost text is 0 in mathed)
1099         for (s = depth() - 1; s >= 0; --s)
1100                 if (operator[](s).text())
1101                         break;
1102         CursorSlice const & sl = operator[](s);
1103         LyXText const & text = *sl.text();
1104         LyXFont font = text.getPar(sl.pit()).getFont(
1105                 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1106         return font.language()->encoding();
1107 }
1108
1109
1110 void LCursor::undispatched()
1111 {
1112         disp_.dispatched(false);
1113 }
1114
1115
1116 void LCursor::dispatched()
1117 {
1118         disp_.dispatched(true);
1119 }
1120
1121
1122 void LCursor::needsUpdate()
1123 {
1124         disp_.update(true);
1125 }
1126
1127
1128 void LCursor::noUpdate()
1129 {
1130         disp_.update(false);
1131 }
1132
1133
1134 LyXFont LCursor::getFont() const
1135 {
1136         // HACK. far from being perfect...
1137         int s = 0;
1138         // go up until first non-0 text is hit
1139         // (innermost text is 0 in mathed)
1140         for (s = depth() - 1; s >= 0; --s)
1141                 if (operator[](s).text())
1142                         break;
1143         CursorSlice const & sl = operator[](s);
1144         LyXText const & text = *sl.text();
1145         LyXFont font = text.getPar(sl.pit()).getFont(
1146                 bv().buffer()->params(),
1147                 sl.pos(),
1148                 outerFont(sl.pit(), text.paragraphs()));
1149
1150         return font;
1151 }
1152
1153
1154 void LCursor::fixIfBroken()
1155 {
1156         // find out last good level
1157         LCursor copy = *this;
1158         size_t newdepth = depth();
1159         while (!copy.empty()) {
1160                 if (copy.idx() > copy.lastidx()) {
1161                         lyxerr << "wrong idx " << copy.idx()
1162                                << ", max is " << copy.lastidx()
1163                                << " at level " << copy.depth()
1164                                << ". Trying to correct this."  << endl;
1165                         newdepth = copy.depth() - 1;
1166                 }
1167                 else if (copy.pit() > copy.lastpit()) {
1168                         lyxerr << "wrong pit " << copy.pit()
1169                                << ", max is " << copy.lastpit()
1170                                << " at level " << copy.depth()
1171                                << ". Trying to correct this."  << endl;
1172                         newdepth = copy.depth() - 1;
1173                 }
1174                 else if (copy.pos() > copy.lastpos()) {
1175                         lyxerr << "wrong pos " << copy.pos()
1176                                << ", max is " << copy.lastpos()
1177                                << " at level " << copy.depth()
1178                                << ". Trying to correct this."  << endl;
1179                         newdepth = copy.depth() - 1;
1180                 }
1181                 copy.pop();
1182         }
1183         // shrink cursor to a size where everything is valid, possibly
1184         // leaving insets
1185         while (depth() > newdepth) {
1186                 pop();
1187                 lyxerr << "correcting cursor to level " << depth() << endl;
1188         }
1189 }