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