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