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