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