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