]> git.lyx.org Git - lyx.git/blob - src/cursor.C
small cosmetic fix and removing some debug output
[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         // Open all collapsed insets
412         for (int i = depth() - 1; i >= 0; --i)
413                 operator[](i).inset().setStatus(*this, InsetBase::Open);
414 }
415
416
417 void LCursor::clearSelection()
418 {
419         selection() = false;
420         mark() = false;
421         resetAnchor();
422         bv().unsetXSel();
423 }
424
425
426 int & LCursor::x_target()
427 {
428         return x_target_;
429 }
430
431
432 int LCursor::x_target() const
433 {
434         return x_target_;
435 }
436
437
438 void LCursor::clearTargetX()
439 {
440         x_target_ = -1;
441 }
442
443
444
445 void LCursor::info(std::ostream & os) const
446 {
447         for (int i = 1, n = depth(); i < n; ++i) {
448                 operator[](i).inset().infoize(os);
449                 os << "  ";
450         }
451         if (pos() != 0)
452                 prevInset()->infoize2(os);
453         // overwite old message
454         os << "                    ";
455 }
456
457
458 void LCursor::selHandle(bool sel)
459 {
460         //lyxerr << "LCursor::selHandle" << endl;
461         if (sel == selection())
462                 return;
463
464         resetAnchor();
465         selection() = sel;
466 }
467
468
469 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
470 {
471         os << "\n cursor:                                | anchor:\n";
472         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
473                 os << " " << cur[i] << " | ";
474                 if (i < cur.anchor_.depth())
475                         os << cur.anchor_[i];
476                 else
477                         os << "-------------------------------";
478                 os << "\n";
479         }
480         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
481                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
482         }
483         os << " selection: " << cur.selection_
484            << " x_target: " << cur.x_target_ << endl;
485         return os;
486 }
487
488
489
490
491 ///////////////////////////////////////////////////////////////////
492 //
493 // The part below is the non-integrated rest of the original math
494 // cursor. This should be either generalized for texted or moved
495 // back to mathed (in most cases to MathNestInset).
496 //
497 ///////////////////////////////////////////////////////////////////
498
499 #include "mathed/math_charinset.h"
500 #include "mathed/math_factory.h"
501 #include "mathed/math_gridinset.h"
502 #include "mathed/math_macroarg.h"
503 #include "mathed/math_mathmlstream.h"
504 #include "mathed/math_scriptinset.h"
505 #include "mathed/math_support.h"
506 #include "mathed/math_unknowninset.h"
507
508 //#define FILEDEBUG 1
509
510
511 bool LCursor::isInside(InsetBase const * p)
512 {
513         for (size_t i = 0; i != depth(); ++i)
514                 if (&operator[](i).inset() == p)
515                         return true;
516         return false;
517 }
518
519
520 void LCursor::leaveInset(InsetBase const & inset)
521 {
522         for (size_t i = 0; i != depth(); ++i) {
523                 if (&operator[](i).inset() == &inset) {
524                         resize(i);
525                         return;
526                 }
527         }
528 }
529
530
531 bool LCursor::openable(MathAtom const & t) const
532 {
533         if (!t->isActive())
534                 return false;
535
536         if (t->lock())
537                 return false;
538
539         if (!selection())
540                 return true;
541
542         // we can't move into anything new during selection
543         if (depth() >= anchor_.depth())
544                 return false;
545         if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
546                 return false;
547
548         return true;
549 }
550
551
552 void LCursor::setScreenPos(int x, int y)
553 {
554         x_target() = x;
555         bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
556 }
557
558
559
560 void LCursor::plainErase()
561 {
562         cell().erase(pos());
563 }
564
565
566 void LCursor::markInsert()
567 {
568         insert(char(0));
569 }
570
571
572 void LCursor::markErase()
573 {
574         cell().erase(pos());
575 }
576
577
578 void LCursor::plainInsert(MathAtom const & t)
579 {
580         cell().insert(pos(), t);
581         ++pos();
582 }
583
584
585 void LCursor::insert(string const & str)
586 {
587         for_each(str.begin(), str.end(),
588                  boost::bind(static_cast<void(LCursor::*)(char)>
589                              (&LCursor::insert), this, _1));
590 }
591
592
593 void LCursor::insert(char c)
594 {
595         //lyxerr << "LCursor::insert char '" << c << "'" << endl;
596         BOOST_ASSERT(!empty());
597         if (inMathed()) {
598                 lyx::cap::selClearOrDel(*this);
599                 insert(new MathCharInset(c));
600         } else {
601                 text()->insertChar(*this, c);
602         }
603 }
604
605
606 void LCursor::insert(MathAtom const & t)
607 {
608         //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
609         macroModeClose();
610         lyx::cap::selClearOrDel(*this);
611         plainInsert(t);
612 }
613
614
615 void LCursor::insert(InsetBase * inset)
616 {
617         if (inMathed())
618                 insert(MathAtom(inset));
619         else
620                 text()->insertInset(*this, inset);
621 }
622
623
624 void LCursor::niceInsert(string const & t)
625 {
626         MathArray ar;
627         asArray(t, ar);
628         if (ar.size() == 1)
629                 niceInsert(ar[0]);
630         else
631                 insert(ar);
632 }
633
634
635 void LCursor::niceInsert(MathAtom const & t)
636 {
637         macroModeClose();
638         string const safe = lyx::cap::grabAndEraseSelection(*this);
639         plainInsert(t);
640         // enter the new inset and move the contents of the selection if possible
641         if (t->isActive()) {
642                 posLeft();
643                 // be careful here: don't use 'pushLeft(t)' as this we need to
644                 // push the clone, not the original
645                 pushLeft(*nextInset());
646                 paste(safe);
647         }
648 }
649
650
651 void LCursor::insert(MathArray const & ar)
652 {
653         macroModeClose();
654         if (selection())
655                 lyx::cap::eraseSelection(*this);
656         cell().insert(pos(), ar);
657         pos() += ar.size();
658 }
659
660
661 bool LCursor::backspace()
662 {
663         autocorrect() = false;
664
665         if (selection()) {
666                 lyx::cap::selDel(*this);
667                 return true;
668         }
669
670         if (pos() == 0) {
671                 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
672                         return false;
673                 pullArg();
674                 return true;
675         }
676
677         if (inMacroMode()) {
678                 MathUnknownInset * p = activeMacro();
679                 if (p->name().size() > 1) {
680                         p->setName(p->name().substr(0, p->name().size() - 1));
681                         return true;
682                 }
683         }
684
685         if (pos() != 0 && prevAtom()->nargs() > 0) {
686                 // let's require two backspaces for 'big stuff' and
687                 // highlight on the first
688                 resetAnchor();
689                 selection() = true;
690                 --pos();
691         } else {
692                 --pos();
693                 plainErase();
694         }
695         return true;
696 }
697
698
699 bool LCursor::erase()
700 {
701         autocorrect() = false;
702         if (inMacroMode())
703                 return true;
704
705         if (selection()) {
706                 lyx::cap::selDel(*this);
707                 return true;
708         }
709
710         // delete empty cells if possible
711         if (pos() == lastpos() && inset().idxDelete(idx()))
712                 return true;
713
714         // special behaviour when in last position of cell
715         if (pos() == lastpos()) {
716                 bool one_cell = inset().nargs() == 1;
717                 if (one_cell && depth() == 1 && lastpos() == 0)
718                         return false;
719                 // remove markup
720                 if (one_cell)
721                         pullArg();
722                 else
723                         inset().idxGlue(idx());
724                 return true;
725         }
726
727         // 'clever' UI hack: only erase large items if previously slected
728         if (pos() != lastpos() && inset().nargs() > 0) {
729                 resetAnchor();
730                 selection() = true;
731                 ++pos();
732         } else {
733                 plainErase();
734         }
735
736         return true;
737 }
738
739
740 bool LCursor::up()
741 {
742         macroModeClose();
743         DocIterator save = *this;
744         if (goUpDown(true))
745                 return true;
746         setCursor(save);
747         autocorrect() = false;
748         return selection();
749 }
750
751
752 bool LCursor::down()
753 {
754         macroModeClose();
755         DocIterator save = *this;
756         if (goUpDown(false))
757                 return true;
758         setCursor(save);
759         autocorrect() = false;
760         return selection();
761 }
762
763
764 void LCursor::macroModeClose()
765 {
766         if (!inMacroMode())
767                 return;
768         MathUnknownInset * p = activeMacro();
769         p->finalize();
770         string const s = p->name();
771         --pos();
772         cell().erase(pos());
773
774         // do nothing if the macro name is empty
775         if (s == "\\")
776                 return;
777
778         string const name = s.substr(1);
779
780         // prevent entering of recursive macros
781         // FIXME: this is only a weak attempt... only prevents immediate
782         // recursion
783         InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
784         if (macro && macro->getInsetName() == name)
785                 lyxerr << "can't enter recursive macro" << endl;
786
787         plainInsert(createMathInset(name));
788 }
789
790
791 string LCursor::macroName()
792 {
793         return inMacroMode() ? activeMacro()->name() : string();
794 }
795
796
797 void LCursor::handleNest(MathAtom const & a, int c)
798 {
799         //lyxerr << "LCursor::handleNest: " << c << endl;
800         MathAtom t = a;
801         asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
802         insert(t);
803         posLeft();
804         pushLeft(*nextInset());
805 }
806
807
808 int LCursor::targetX() const
809 {
810         if (x_target() != -1)
811                 return x_target();
812         int x = 0;
813         int y = 0;
814         getPos(x, y);
815         return x;
816 }
817
818
819 void LCursor::setTargetX()
820 {
821         // For now this is good enough. A better solution would be to
822         // avoid this rebreak by setting cursorX only after drawing
823         bottom().text()->redoParagraph(bottom().pit());
824         int x;
825         int y;
826         getPos(x, y);
827         x_target_ = x;
828 }
829
830
831 bool LCursor::inMacroMode() const
832 {
833         if (pos() == 0)
834                 return false;
835         MathUnknownInset const * p = prevAtom()->asUnknownInset();
836         return p && !p->final();
837 }
838
839
840 MathUnknownInset * LCursor::activeMacro()
841 {
842         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
843 }
844
845
846 void LCursor::pullArg()
847 {
848 #ifdef WITH_WARNINGS
849 #warning Look here
850 #endif
851         MathArray ar = cell();
852         if (popLeft() && inMathed()) {
853                 plainErase();
854                 cell().insert(pos(), ar);
855                 resetAnchor();
856         } else {
857                 //formula()->mutateToText();
858         }
859 }
860
861
862 void LCursor::touch()
863 {
864 #ifdef WITH_WARNINGS
865 #warning look here
866 #endif
867 #if 0
868         DocIterator::const_iterator it = begin();
869         DocIterator::const_iterator et = end();
870         for ( ; it != et; ++it)
871                 it->cell().touch();
872 #endif
873 }
874
875
876 void LCursor::normalize()
877 {
878         if (idx() >= nargs()) {
879                 lyxerr << "this should not really happen - 1: "
880                        << idx() << ' ' << nargs()
881                        << " in: " << &inset() << endl;
882         }
883         idx() = min(idx(), lastidx());
884
885         if (pos() > lastpos()) {
886                 lyxerr << "this should not really happen - 2: "
887                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
888                        << " in atom: '";
889                 WriteStream wi(lyxerr, false, true);
890                 inset().asMathInset()->write(wi);
891                 lyxerr << endl;
892         }
893         pos() = min(pos(), lastpos());
894 }
895
896
897 bool LCursor::goUpDown(bool up)
898 {
899         // Be warned: The 'logic' implemented in this function is highly
900         // fragile. A distance of one pixel or a '<' vs '<=' _really
901         // matters. So fiddle around with it only if you think you know
902         // what you are doing!
903
904         int xo = 0;
905         int yo = 0;
906         getPos(xo, yo);
907
908         // check if we had something else in mind, if not, this is the future goal
909         if (x_target() == -1)
910                 x_target() = xo;
911         else
912                 xo = x_target();
913
914         // try neigbouring script insets
915         if (!selection()) {
916                 // try left
917                 if (pos() != 0) {
918                         MathScriptInset const * p = prevAtom()->asScriptInset();
919                         if (p && p->has(up)) {
920                                 --pos();
921                                 push(inset());
922                                 idx() = up; // the superscript has index 1
923                                 pos() = lastpos();
924                                 //lyxerr << "updown: handled by scriptinset to the left" << endl;
925                                 return true;
926                         }
927                 }
928
929                 // try right
930                 if (pos() != lastpos()) {
931                         MathScriptInset const * p = nextAtom()->asScriptInset();
932                         if (p && p->has(up)) {
933                                 push(inset());
934                                 idx() = up;
935                                 pos() = 0;
936                                 //lyxerr << "updown: handled by scriptinset to the right" << endl;
937                                 return true;
938                         }
939                 }
940         }
941
942         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
943         //if (up)
944         //      yhigh = yo - 4;
945         //else
946         //      ylow = yo + 4;
947         //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
948         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
949         //      return true;
950         //}
951
952         // try to find an inset that knows better then we
953         while (true) {
954                 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
955                 // ask inset first
956                 if (inset().idxUpDown(*this, up)) {
957                         // try to find best position within this inset
958                         if (!selection())
959                                 setCursor(bruteFind2(*this, xo, yo));
960                         return true;
961                 }
962
963                 // no such inset found, just take something "above"
964                 //lyxerr << "updown: handled by strange case" << endl;
965                 if (!popLeft()) {
966                         int ylow  = up ? 0 : yo + 1;
967                         int yhigh = up ? yo - 1 : bv().workHeight();
968                         return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
969                 }
970
971                 // any improvement so far?
972                 int xnew;
973                 int 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 = depth() - 1; s >= 0; --s)
1103                 if (operator[](s).text())
1104                         break;
1105         CursorSlice const & sl = operator[](s);
1106         LyXText const & 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 }
1135
1136
1137 LyXFont LCursor::getFont() const
1138 {
1139         // HACK. far from being perfect...
1140         int s = 0;
1141         // go up until first non-0 text is hit
1142         // (innermost text is 0 in mathed)
1143         for (s = depth() - 1; s >= 0; --s)
1144                 if (operator[](s).text())
1145                         break;
1146         CursorSlice const & sl = operator[](s);
1147         LyXText const & text = *sl.text();
1148         LyXFont font = text.getPar(sl.pit()).getFont(
1149                 bv().buffer()->params(),
1150                 sl.pos(),
1151                 outerFont(sl.pit(), text.paragraphs()));
1152
1153         return font;
1154 }
1155
1156
1157 void LCursor::fixIfBroken()
1158 {
1159         // find out last good level
1160         LCursor copy = *this;
1161         size_t newdepth = depth();
1162         while (!copy.empty()) {
1163                 if (copy.idx() > copy.lastidx()) {
1164                         lyxerr << "wrong idx " << copy.idx()
1165                                << ", max is " << copy.lastidx()
1166                                << " at level " << copy.depth()
1167                                << ". Trying to correct this."  << endl;
1168                         newdepth = copy.depth() - 1;
1169                 }
1170                 else if (copy.pit() > copy.lastpit()) {
1171                         lyxerr << "wrong pit " << copy.pit()
1172                                << ", max is " << copy.lastpit()
1173                                << " at level " << copy.depth()
1174                                << ". Trying to correct this."  << endl;
1175                         newdepth = copy.depth() - 1;
1176                 }
1177                 else if (copy.pos() > copy.lastpos()) {
1178                         lyxerr << "wrong pos " << copy.pos()
1179                                << ", max is " << copy.lastpos()
1180                                << " at level " << copy.depth()
1181                                << ". Trying to correct this."  << endl;
1182                         newdepth = copy.depth() - 1;
1183                 }
1184                 copy.pop();
1185         }
1186         // shrink cursor to a size where everything is valid, possibly
1187         // leaving insets
1188         while (depth() > newdepth) {
1189                 pop();
1190                 lyxerr << "correcting cursor to level " << depth() << endl;
1191         }
1192 }