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