]> git.lyx.org Git - lyx.git/blob - src/cursor.C
e712ea42d67f91c744fa8a1d33f710f61ae1711f
[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 "buffer.h"
16 #include "BufferView.h"
17 #include "cursor.h"
18 #include "debug.h"
19 #include "dispatchresult.h"
20 #include "funcrequest.h"
21 #include "iterators.h"
22 #include "lfuns.h"
23 #include "lyxfunc.h" // only for setMessage()
24 #include "lyxrc.h"
25 #include "lyxrow.h"
26 #include "lyxtext.h"
27 #include "paragraph.h"
28
29 #include "insets/updatableinset.h"
30 #include "insets/insettabular.h"
31 #include "insets/insettext.h"
32
33 #include "mathed/math_data.h"
34 #include "mathed/math_hullinset.h"
35 #include "mathed/math_support.h"
36
37 #include "support/limited_stack.h"
38 #include "support/std_sstream.h"
39
40 #include "frontends/LyXView.h"
41
42 #include <boost/assert.hpp>
43
44 using std::string;
45 using std::vector;
46 using std::endl;
47 #ifndef CXX_GLOBAL_CSTD
48 using std::isalpha;
49 #endif
50 using std::min;
51 using std::swap;
52
53
54
55 // our own cut buffer
56 limited_stack<string> theCutBuffer;
57
58
59 LCursor::LCursor(BufferView & bv)
60         : DocumentIterator(bv), anchor_(bv),
61           cached_y_(0), x_target_(-1), selection_(false), mark_(false)
62 {}
63
64
65 void LCursor::reset()
66 {
67         clear();
68         push_back(CursorSlice());
69         anchor_.clear();
70         anchor_.push_back(CursorSlice());
71         cached_y_ = 0;
72         clearTargetX();
73         selection_ = false;
74         mark_ = false;
75 }
76
77
78 void LCursor::setCursor(DocumentIterator const & cur, bool sel)
79 {
80         // this (intentionally) does not touch the anchor
81         DocumentIterator::operator=(cur);
82         selection() = sel;
83 }
84
85
86 DispatchResult LCursor::dispatch(FuncRequest const & cmd0)
87 {
88         lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
89         BOOST_ASSERT(pos() <= lastpos());
90         BOOST_ASSERT(idx() <= lastidx());
91         BOOST_ASSERT(par() <= lastpar());
92         FuncRequest cmd = cmd0;
93         nopop_ = false;
94         DocumentIterator orig = *this;
95         disp_.update(true);
96         disp_.val(NONE);
97         while (size() != 1) {
98                 // the inset's dispatch() is supposed to reset the update and
99                 // val flags if necessary 
100                 inset()->dispatch(*this, cmd);
101                 
102                 // "Mutate" the request for semi-handled requests that need
103                 // additional handling in outer levels.
104                 switch (disp_.val()) {
105                         case NONE:
106                                 // the inset handled the event fully
107                                 return DispatchResult(true, true);
108                         case FINISHED_LEFT:
109                                 // the inset handled the event partially
110                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
111                                 break;
112                         case FINISHED_RIGHT:
113                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
114                                 break;
115                         case FINISHED_UP:
116                                 cmd = FuncRequest(LFUN_FINISHED_UP);
117                                 break;
118                         case FINISHED_DOWN:
119                                 cmd = FuncRequest(LFUN_FINISHED_DOWN);
120                                 break;
121                         default:
122                                 //lyxerr << "not handled on level " << depth()
123                                 //      << " val: " << disp_.val() << endl;
124                                 break;
125                 }
126                 pop();
127         }
128         bv().text()->dispatch(*this, cmd);
129         if (nopop_)
130                 setCursor(orig, false);
131         //lyxerr << "   result: " << res.val() << endl;
132         return disp_;
133 }
134
135
136 bool LCursor::getStatus(FuncRequest const & cmd, FuncStatus & status)
137 {
138         lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
139         DocumentIterator orig = *this;
140         BOOST_ASSERT(pos() <= lastpos());
141         BOOST_ASSERT(idx() <= lastidx());
142         BOOST_ASSERT(par() <= lastpar());
143         for ( ; size() != 0; pop_back()) {
144                 // the inset's getStatus() will return 'true' if it made
145                 // a definitive decision on whether it want to handle the
146                 // request or not. The result of this decision is put into
147                 // the 'status' parameter.
148                 bool const res = inset()->getStatus(*this, cmd, status);
149                 if (res) {
150                         setCursor(orig, false);
151                         return true;
152                 }
153         }
154         bool const res = bv().text()->getStatus(*this, cmd, status);
155         setCursor(orig, false);
156         return res;
157 }
158
159
160 BufferView & LCursor::bv() const
161 {
162         return DocumentIterator::bv();
163 }
164
165
166 /*
167 void LCursor::pop(int depth)
168 {
169         while (int(size()) > depth + 1)
170                 pop();
171         lyxerr << "LCursor::pop() result: " << *this << endl;
172 }
173 */
174
175
176 void LCursor::pop()
177 {
178         BOOST_ASSERT(size() >= 1);
179         pop_back();
180         anchor_.pop_back();
181 }
182
183
184 void LCursor::push(InsetBase * p)
185 {
186         push_back(CursorSlice(p));
187 }
188
189
190 void LCursor::pushLeft(InsetBase * p)
191 {
192         BOOST_ASSERT(!empty());
193         //lyxerr << "Entering inset " << t << " left" << endl;
194         push(p);
195         p->idxFirst(*this);
196 }
197
198
199 bool LCursor::popLeft()
200 {
201         BOOST_ASSERT(!empty());
202         //lyxerr << "Leaving inset to the left" << endl;
203         if (depth() <= 1) {
204                 if (depth() == 1)
205                         inset()->notifyCursorLeaves(idx());
206                 return false;
207         }
208         inset()->notifyCursorLeaves(idx());
209         pop();
210         return true;
211 }
212
213
214 bool LCursor::popRight()
215 {
216         BOOST_ASSERT(!empty());
217         //lyxerr << "Leaving inset to the right" << endl;
218         if (depth() <= 1) {
219                 if (depth() == 1)
220                         inset()->notifyCursorLeaves(idx());
221                 return false;
222         }
223         inset()->notifyCursorLeaves(idx());
224         pop();
225         ++pos();
226         return true;
227 }
228
229
230 int LCursor::currentMode()
231 {
232         BOOST_ASSERT(!empty());
233         for (int i = size() - 1; i >= 1; --i) {
234                 int res = operator[](i).inset()->currentMode();
235                 if (res != MathInset::UNDECIDED_MODE)
236                         return res;
237         }
238         return MathInset::TEXT_MODE;
239 }
240
241
242 void LCursor::updatePos()
243 {
244         BOOST_ASSERT(!empty());
245         if (size() > 1)
246                 cached_y_ = bv().top_y() + back().inset()->yo();
247                 //cached_y_ = back().inset()->yo();
248 }
249
250
251 void LCursor::getDim(int & asc, int & des) const
252 {
253         BOOST_ASSERT(!empty());
254         if (inMathed()) {
255                 BOOST_ASSERT(inset());
256                 BOOST_ASSERT(inset()->asMathInset());
257                 //inset()->asMathInset()->getCursorDim(asc, des);
258                 asc = 10;
259                 des = 10;
260         } else {
261                 Row const & row = textRow();
262                 asc = row.baseline();
263                 des = row.height() - asc;
264         }
265 }
266
267
268 void LCursor::getPos(int & x, int & y) const
269 {
270         BOOST_ASSERT(!empty());
271         x = 0;
272         y = 0;
273         if (size() == 1) {
274                 x = bv().text()->cursorX(front());
275                 y = bv().text()->cursorY(front());
276         } else {
277                 if (!inset()) {
278                         lyxerr << "#### LCursor::getPos: " << *this << endl;
279                         BOOST_ASSERT(inset());
280                 }
281                 inset()->getCursorPos(back(), x, y);
282                 // getCursorPos gives _screen_ coordinates. We need to add
283                 // top_y to get document coordinates. This is hidden in cached_y_.
284                 //y += cached_y_ - inset()->yo();
285                 // The rest is non-obvious. The reason we have to have these
286                 // extra computation is that the getCursorPos() calls rely
287                 // on the inset's own knowledge of its screen position.
288                 // If we scroll up or down in a big enough increment,
289                 // inset->draw() is not called: this doesn't update
290                 // inset.yo_, so getCursor() returns an old value.
291                 // Ugly as you like.
292         }
293         //lyxerr << "#### LCursor::getPos: " << *this 
294         // << " x: " << x << " y: " << y << endl;
295 }
296
297
298 void LCursor::paste(string const & data)
299 {
300         dispatch(FuncRequest(LFUN_PASTE, data));
301 }
302
303
304 void LCursor::resetAnchor()
305 {
306         anchor_ = *this;
307 }
308
309
310
311 bool LCursor::posLeft()
312 {
313         if (pos() == 0)
314                 return false;
315         --pos();
316         return true;
317 }
318
319
320 bool LCursor::posRight()
321 {
322         if (pos() == lastpos())
323                 return false;
324         ++pos();
325         return true;
326 }
327
328
329 CursorSlice & LCursor::anchor()
330 {
331         return anchor_.back();
332 }
333
334
335 CursorSlice const & LCursor::anchor() const
336 {
337         return anchor_.back();
338 }
339
340
341 CursorSlice const & LCursor::selBegin() const
342 {
343         if (!selection())
344                 return back();
345         return anchor() < back() ? anchor() : back();
346 }
347
348
349 CursorSlice & LCursor::selBegin()
350 {
351         if (!selection())
352                 return back();
353         // can't use std::min as this returns a const ref
354         return anchor() < back() ? anchor() : back();
355 }
356
357
358 CursorSlice const & LCursor::selEnd() const
359 {
360         if (!selection())
361                 return back();
362         return anchor() > back() ? anchor() : back();
363 }
364
365
366 CursorSlice & LCursor::selEnd()
367 {
368         if (!selection())
369                 return back();
370         // can't use std::min as this returns a const ref
371         return anchor() > back() ? anchor() : back();
372 }
373
374
375 void LCursor::setSelection()
376 {
377         selection() = true;
378         // a selection with no contents is not a selection
379         if (par() == anchor().par() && pos() == anchor().pos())
380                 selection() = false;
381 }
382
383
384 void LCursor::setSelection(DocumentIterator const & where, size_t n)
385 {
386         selection() = true;
387         setCursor(where, false);
388         anchor_ = where;
389         pos() += n;
390 }
391
392
393 void LCursor::clearSelection()
394 {
395         selection() = false;
396         mark() = false;
397         resetAnchor();
398         bv().unsetXSel();
399 }
400
401
402 int & LCursor::x_target()
403 {
404         return x_target_;
405 }
406
407
408 int LCursor::x_target() const
409 {
410         return x_target_;
411 }
412
413
414 void LCursor::clearTargetX()
415 {
416         x_target_ = -1;
417 }
418
419
420
421 void LCursor::info(std::ostream & os) const
422 {
423         for (int i = 1, n = depth(); i < n; ++i) {
424                 operator[](i).inset()->infoize(os);
425                 os << "  ";
426         }
427         if (pos() != 0)
428                 prevInset()->infoize2(os);
429         // overwite old message
430         os << "                    ";
431 }
432
433
434 namespace {
435
436 void region(CursorSlice const & i1, CursorSlice const & i2,
437         LCursor::row_type & r1, LCursor::row_type & r2,
438         LCursor::col_type & c1, LCursor::col_type & c2)
439 {
440         InsetBase * p = i1.inset();
441         c1 = p->col(i1.idx_);
442         c2 = p->col(i2.idx_);
443         if (c1 > c2)
444                 swap(c1, c2);
445         r1 = p->row(i1.idx_);
446         r2 = p->row(i2.idx_);
447         if (r1 > r2)
448                 swap(r1, r2);
449 }
450
451 }
452
453
454 string LCursor::grabSelection()
455 {
456         if (!selection())
457                 return string();
458
459         CursorSlice i1 = selBegin();
460         CursorSlice i2 = selEnd();
461
462         if (i1.idx_ == i2.idx_) {
463                 if (i1.inset()->asMathInset()) {
464                         MathArray::const_iterator it = i1.cell().begin();
465                         return asString(MathArray(it + i1.pos_, it + i2.pos_));
466                 } else {
467                         return "unknown selection 1";
468                 }
469         }
470
471         row_type r1, r2;
472         col_type c1, c2;
473         region(i1, i2, r1, r2, c1, c2);
474
475         string data;
476         if (i1.inset()->asMathInset()) {
477                 for (row_type row = r1; row <= r2; ++row) {
478                         if (row > r1)
479                                 data += "\\\\";
480                         for (col_type col = c1; col <= c2; ++col) {
481                                 if (col > c1)
482                                         data += '&';
483                                 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
484                         }
485                 }
486         } else {
487                 data = "unknown selection 2";
488         }
489         return data;
490 }
491
492
493 void LCursor::eraseSelection()
494 {
495         //lyxerr << "LCursor::eraseSelection" << endl;
496         CursorSlice const & i1 = selBegin();
497         CursorSlice const & i2 = selEnd();
498 #warning FIXME
499         if (i1.inset()->asMathInset()) {
500                 if (i1.idx_ == i2.idx_) {
501                         i1.cell().erase(i1.pos_, i2.pos_);
502                 } else {
503                         MathInset * p = i1.asMathInset();
504                         row_type r1, r2;
505                         col_type c1, c2;
506                         region(i1, i2, r1, r2, c1, c2);
507                         for (row_type row = r1; row <= r2; ++row)
508                                 for (col_type col = c1; col <= c2; ++col)
509                                         p->cell(p->index(row, col)).clear();
510                 }
511                 back() = i1;
512         } else {
513                 lyxerr << "can't erase this selection 1" << endl;
514         }
515         //lyxerr << "LCursor::eraseSelection end" << endl;
516 }
517
518
519 string LCursor::grabAndEraseSelection()
520 {
521         if (!selection())
522                 return string();
523         string res = grabSelection();
524         eraseSelection();
525         selection() = false;
526         return res;
527 }
528
529
530 void LCursor::selClear()
531 {
532         resetAnchor();
533         clearSelection();
534 }
535
536
537 void LCursor::selCopy()
538 {
539         if (selection()) {
540                 theCutBuffer.push(grabSelection());
541                 selection() = false;
542         } else {
543                 //theCutBuffer.erase();
544         }
545 }
546
547
548 void LCursor::selCut()
549 {
550         theCutBuffer.push(grabAndEraseSelection());
551 }
552
553
554 void LCursor::selDel()
555 {
556         //lyxerr << "LCursor::selDel" << endl;
557         if (selection()) {
558                 eraseSelection();
559                 selection() = false;
560         }
561 }
562
563
564 void LCursor::selPaste(size_t n)
565 {
566         selClearOrDel();
567         if (n < theCutBuffer.size())
568                 paste(theCutBuffer[n]);
569         //grabSelection();
570         selection() = false;
571 }
572
573
574 void LCursor::selHandle(bool sel)
575 {
576         //lyxerr << "LCursor::selHandle" << endl;
577         if (sel == selection())
578                 return;
579         resetAnchor();
580         selection() = sel;
581 }
582
583
584 void LCursor::selClearOrDel()
585 {
586         //lyxerr << "LCursor::selClearOrDel" << endl;
587         if (lyxrc.auto_region_delete)
588                 selDel();
589         else
590                 selection() = false;
591 }
592
593
594 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
595 {
596         for (size_t i = 0, n = cur.size(); i != n; ++i)
597                 os << " " << cur.operator[](i) << " | " << cur.anchor_[i] << "\n";
598         os << " selection: " << cur.selection_ << endl;
599         return os;
600 }
601
602
603
604
605 ///////////////////////////////////////////////////////////////////
606 //
607 // The part below is the non-integrated rest of the original math
608 // cursor. This should be either generalized for texted or moved
609 // back to mathed (in most cases to MathNestInset).
610 //
611 ///////////////////////////////////////////////////////////////////
612
613 #include "mathed/math_charinset.h"
614 #include "mathed/math_factory.h"
615 #include "mathed/math_gridinset.h"
616 #include "mathed/math_macroarg.h"
617 #include "mathed/math_macrotemplate.h"
618 #include "mathed/math_mathmlstream.h"
619 #include "mathed/math_scriptinset.h"
620 #include "mathed/math_support.h"
621 #include "mathed/math_unknowninset.h"
622
623 //#define FILEDEBUG 1
624
625
626 bool LCursor::isInside(InsetBase const * p)
627 {
628         for (unsigned i = 0; i < depth(); ++i)
629                 if (operator[](i).inset() == p)
630                         return true;
631         return false;
632 }
633
634
635 bool LCursor::openable(MathAtom const & t) const
636 {
637         if (!t->isActive())
638                 return false;
639
640         if (t->lock())
641                 return false;
642
643         if (!selection())
644                 return true;
645
646         // we can't move into anything new during selection
647         if (depth() == anchor_.size())
648                 return false;
649         if (!ptr_cmp(t.nucleus(), anchor_[depth()].inset()))
650                 return false;
651
652         return true;
653 }
654
655
656 bool positionable(DocumentIterator const & cursor,
657         DocumentIterator const & anchor)
658 {
659         // avoid deeper nested insets when selecting
660         if (cursor.size() > anchor.size())
661                 return false;
662
663         // anchor might be deeper, should have same path then
664         for (size_t i = 0; i < cursor.size(); ++i)
665                 if (cursor[i].inset() != anchor[i].inset())
666                         return false;
667
668         // position should be ok.
669         return true;
670 }
671
672
673 void LCursor::setScreenPos(int x, int y)
674 {
675         bool res = bruteFind(x, y, formula()->xlow(), formula()->xhigh(),
676                 formula()->ylow(), formula()->yhigh());
677         if (!res) {
678                 // this can happen on creation of "math-display"
679                 idx() = 0;
680                 pos() = 0;
681         }
682         clearTargetX();
683 }
684
685
686
687 void LCursor::plainErase()
688 {
689         cell().erase(pos());
690 }
691
692
693 void LCursor::markInsert()
694 {
695         cell().insert(pos(), MathAtom(new MathCharInset(0)));
696 }
697
698
699 void LCursor::markErase()
700 {
701         cell().erase(pos());
702 }
703
704
705 void LCursor::plainInsert(MathAtom const & t)
706 {
707         cell().insert(pos(), t);
708         ++pos();
709 }
710
711
712 void LCursor::insert(string const & str)
713 {
714         lyxerr << "LCursor::insert str '" << str << "'" << endl;
715         selClearOrDel();
716 #if 0
717         for (string::const_iterator it = str.begin(); it != str.end(); ++it)
718                 plainInsert(MathAtom(new MathCharInset(*it)));
719 #else
720         MathArray ar;
721         asArray(str, ar);
722         insert(ar);
723 #endif
724 }
725
726
727 void LCursor::insert(char c)
728 {
729         //lyxerr << "LCursor::insert char '" << c << "'" << endl;
730         selClearOrDel();
731         plainInsert(MathAtom(new MathCharInset(c)));
732 }
733
734
735 void LCursor::insert(MathAtom const & t)
736 {
737         //lyxerr << "LCursor::insert MathAtom: " << endl;
738         macroModeClose();
739         selClearOrDel();
740         plainInsert(t);
741 }
742
743
744 void LCursor::insert(InsetBase * inset)
745 {
746         if (inMathed())
747                 insert(MathAtom(inset));
748         else
749                 text()->insertInset(*this, inset);
750 }
751
752
753 void LCursor::niceInsert(string const & t)
754 {
755         MathArray ar;
756         asArray(t, ar);
757         if (ar.size() == 1)
758                 niceInsert(ar[0]);
759         else
760                 insert(ar);
761 }
762
763
764 void LCursor::niceInsert(MathAtom const & t)
765 {
766         macroModeClose();
767         string safe = grabAndEraseSelection();
768         plainInsert(t);
769         // enter the new inset and move the contents of the selection if possible
770         if (t->isActive()) {
771                 posLeft();
772                 // be careful here: don't use 'pushLeft(t)' as this we need to
773                 // push the clone, not the original
774                 pushLeft(nextAtom().nucleus());
775                 paste(safe);
776         }
777 }
778
779
780 void LCursor::insert(MathArray const & ar)
781 {
782         macroModeClose();
783         if (selection())
784                 eraseSelection();
785         cell().insert(pos(), ar);
786         pos() += ar.size();
787 }
788
789
790 bool LCursor::backspace()
791 {
792         autocorrect() = false;
793
794         if (selection()) {
795                 selDel();
796                 return true;
797         }
798
799         if (pos() == 0) {
800                 if (inset()->nargs() == 1 && depth() == 1 && lastpos() == 0)
801                         return false;
802                 pullArg();
803                 return true;
804         }
805
806         if (inMacroMode()) {
807                 MathUnknownInset * p = activeMacro();
808                 if (p->name().size() > 1) {
809                         p->setName(p->name().substr(0, p->name().size() - 1));
810                         return true;
811                 }
812         }
813
814         if (pos() != 0 && prevAtom()->nargs() > 0) {
815                 // let's require two backspaces for 'big stuff' and
816                 // highlight on the first
817                 selection() = true;
818                 --pos();
819         } else {
820                 --pos();
821                 plainErase();
822         }
823         return true;
824 }
825
826
827 bool LCursor::erase()
828 {
829         autocorrect() = false;
830         if (inMacroMode())
831                 return true;
832
833         if (selection()) {
834                 selDel();
835                 return true;
836         }
837
838         // delete empty cells if possible
839         if (pos() == lastpos() && inset()->idxDelete(idx()))
840                 return true;
841
842         // special behaviour when in last position of cell
843         if (pos() == lastpos()) {
844                 bool one_cell = inset()->nargs() == 1;
845                 if (one_cell && depth() == 1 && lastpos() == 0)
846                         return false;
847                 // remove markup
848                 if (one_cell)
849                         pullArg();
850                 else
851                         inset()->idxGlue(idx());
852                 return true;
853         }
854
855         if (pos() != lastpos() && inset()->nargs() > 0) {
856                 selection() = true;
857                 ++pos();
858         } else {
859                 plainErase();
860         }
861
862         return true;
863 }
864
865
866 bool LCursor::up()
867 {
868         macroModeClose();
869         DocumentIterator save = *this;
870         if (goUpDown(true))
871                 return true;
872         setCursor(save, false);
873         autocorrect() = false;
874         return selection();
875 }
876
877
878 bool LCursor::down()
879 {
880         macroModeClose();
881         DocumentIterator save = *this;
882         if (goUpDown(false))
883                 return true;
884         setCursor(save, false);
885         autocorrect() = false;
886         return selection();
887 }
888
889
890 void LCursor::macroModeClose()
891 {
892         if (!inMacroMode())
893                 return;
894         MathUnknownInset * p = activeMacro();
895         p->finalize();
896         string s = p->name();
897         --pos();
898         cell().erase(pos());
899
900         // do nothing if the macro name is empty
901         if (s == "\\")
902                 return;
903
904         string const name = s.substr(1);
905
906         // prevent entering of recursive macros
907         InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
908         if (macro && macro->getInsetName() == name)
909                 lyxerr << "can't enter recursive macro" << endl;
910
911         niceInsert(createMathInset(name));
912 }
913
914
915 string LCursor::macroName()
916 {
917         return inMacroMode() ? activeMacro()->name() : string();
918 }
919
920
921 void LCursor::handleNest(MathAtom const & a, int c)
922 {
923         //lyxerr << "LCursor::handleNest: " << c << endl;
924         MathAtom t = a;
925         asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
926         insert(t);
927         posLeft();
928         pushLeft(nextAtom().nucleus());
929 }
930
931
932 int LCursor::targetX() const
933 {
934         if (x_target() != -1)
935                 return x_target();
936         int x = 0;
937         int y = 0;
938         getPos(x, y);
939         return x;
940 }
941
942
943 MathHullInset * LCursor::formula() const
944 {
945         for (int i = size() - 1; i >= 1; --i) {
946                 MathInset * inset = operator[](i).inset()->asMathInset();
947                 if (inset && inset->asHullInset())
948                         return static_cast<MathHullInset *>(inset);
949         }
950         return 0;
951 }
952
953
954 void LCursor::adjust(pos_type from, int diff)
955 {
956         if (pos() > from)
957                 pos() += diff;
958         if (anchor().pos_ > from)
959                 anchor().pos_ += diff;
960         // just to be on the safe side
961         // theoretically unecessary
962         normalize();
963 }
964
965
966 bool LCursor::inMacroMode() const
967 {
968         if (!pos() != 0)
969                 return false;
970         MathUnknownInset const * p = prevAtom()->asUnknownInset();
971         return p && !p->final();
972 }
973
974
975 MathUnknownInset * LCursor::activeMacro()
976 {
977         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
978 }
979
980
981 bool LCursor::inMacroArgMode() const
982 {
983         return pos() > 0 && prevAtom()->getChar() == '#';
984 }
985
986
987 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
988 {
989         for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
990                 MathInset * m = operator[](i).inset()->asMathInset();
991                 if (!m)
992                         return 0;
993                 MathGridInset * p = m->asGridInset();
994                 if (p) {
995                         idx = operator[](i).idx_;
996                         return p;
997                 }
998         }
999         return 0;
1000 }
1001
1002
1003 void LCursor::pullArg()
1004 {
1005 #warning Look here
1006         MathArray ar = cell();
1007         if (popLeft() && inMathed()) {
1008                 plainErase();
1009                 cell().insert(pos(), ar);
1010                 resetAnchor();
1011         } else {
1012                 //formula()->mutateToText();
1013         }
1014 }
1015
1016
1017 void LCursor::touch()
1018 {
1019 #warning look here
1020 #if 0
1021         DocumentIterator::const_iterator it = begin();
1022         DocumentIterator::const_iterator et = end();
1023         for ( ; it != et; ++it)
1024                 it->cell().touch();
1025 #endif
1026 }
1027
1028
1029 void LCursor::normalize()
1030 {
1031         if (idx() >= nargs()) {
1032                 lyxerr << "this should not really happen - 1: "
1033                        << idx() << ' ' << nargs()
1034                        << " in: " << inset() << endl;
1035         }
1036         idx() = min(idx(), lastidx());
1037
1038         if (pos() > lastpos()) {
1039                 lyxerr << "this should not really happen - 2: "
1040                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1041                        << " in atom: '";
1042                 WriteStream wi(lyxerr, false, true);
1043                 inset()->asMathInset()->write(wi);
1044                 lyxerr << endl;
1045         }
1046         pos() = min(pos(), lastpos());
1047 }
1048
1049
1050 char LCursor::valign()
1051 {
1052         idx_type idx;
1053         MathGridInset * p = enclosingGrid(idx);
1054         return p ? p->valign() : '\0';
1055 }
1056
1057
1058 char LCursor::halign()
1059 {
1060         idx_type idx;
1061         MathGridInset * p = enclosingGrid(idx);
1062         return p ? p->halign(idx % p->ncols()) : '\0';
1063 }
1064
1065
1066 bool LCursor::goUpDown(bool up)
1067 {
1068         // Be warned: The 'logic' implemented in this function is highly
1069         // fragile. A distance of one pixel or a '<' vs '<=' _really
1070         // matters. So fiddle around with it only if you think you know
1071         // what you are doing!
1072   int xo = 0;
1073         int yo = 0;
1074         getPos(xo, yo);
1075
1076         // check if we had something else in mind, if not, this is the future goal
1077         if (x_target() == -1)
1078                 x_target() = xo;
1079         else
1080                 xo = x_target();
1081
1082         // try neigbouring script insets
1083         if (!selection()) {
1084                 // try left
1085                 if (pos() != 0) {
1086                         MathScriptInset const * p = prevAtom()->asScriptInset();
1087                         if (p && p->has(up)) {
1088                                 --pos();
1089                                 push(inset());
1090                                 idx() = up; // the superscript has index 1
1091                                 pos() = lastpos();
1092                                 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1093                                 return true;
1094                         }
1095                 }
1096
1097                 // try right
1098                 if (pos() != lastpos()) {
1099                         MathScriptInset const * p = nextAtom()->asScriptInset();
1100                         if (p && p->has(up)) {
1101                                 push(inset());
1102                                 idx() = up;
1103                                 pos() = 0;
1104                                 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1105                                 return true;
1106                         }
1107                 }
1108         }
1109
1110         // try current cell for e.g. text insets
1111         if (inset()->idxUpDown2(*this, up))
1112                 return true;
1113
1114         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1115         //if (up)
1116         //      yhigh = yo - 4;
1117         //else
1118         //      ylow = yo + 4;
1119         //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1120         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
1121         //      return true;
1122         //}
1123
1124         // try to find an inset that knows better then we
1125         while (1) {
1126                 //lyxerr << "updown: We are in " << inset() << " idx: " << idx() << endl;
1127                 // ask inset first
1128                 if (inset()->idxUpDown(*this, up)) {
1129                         // try to find best position within this inset
1130                         if (!selection())
1131                                 bruteFind2(xo, yo);
1132                         return true;
1133                 }
1134
1135                 // no such inset found, just take something "above"
1136                 //lyxerr << "updown: handled by strange case" << endl;
1137                 if (!popLeft()) {
1138                         return
1139                                 bruteFind(xo, yo,
1140                                         formula()->xlow(),
1141                                         formula()->xhigh(),
1142                                         up ? formula()->ylow() : yo + 4,
1143                                         up ? yo - 4 : formula()->yhigh()
1144                                 );
1145                 }
1146
1147                 // any improvement so far?
1148                 int xnew, ynew;
1149                 getPos(xnew, ynew);
1150                 if (up ? ynew < yo : ynew > yo)
1151                         return true;
1152         }
1153 }
1154
1155
1156 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1157 {
1158         DocumentIterator best_cursor(bv());
1159         double best_dist = 1e10;
1160
1161         DocumentIterator it = bufferBegin(bv());
1162         DocumentIterator et = bufferEnd();
1163         while (1) {
1164                 // avoid invalid nesting when selecting
1165                 if (!selection() || positionable(it, anchor_)) {
1166                         int xo, yo;
1167                         CursorSlice & cur = it.back();
1168                         cur.inset()->getCursorPos(cur, xo, yo);
1169                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1170                                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1171                                 //lyxerr << "x: " << x << " y: " << y << " d: " << endl;
1172                                 // '<=' in order to take the last possible position
1173                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1174                                 if (d <= best_dist) {
1175                                         best_dist   = d;
1176                                         best_cursor = it;
1177                                 }
1178                         }
1179                 }
1180
1181                 if (it == et)
1182                         break;
1183                 it.forwardPos();
1184         }
1185
1186         if (best_dist < 1e10)
1187                 setCursor(best_cursor, false);
1188         return best_dist < 1e10;
1189 }
1190
1191
1192 void LCursor::bruteFind2(int x, int y)
1193 {
1194         double best_dist = 1e10;
1195
1196         DocumentIterator it = *this;
1197         it.back().pos() = 0;
1198         DocumentIterator et = *this;
1199         et.back().pos() = et.back().asMathInset()->cell(et.back().idx_).size();
1200         for (int i = 0; ; ++i) {
1201                 int xo, yo;
1202                 CursorSlice & cur = it.back();
1203                 cur.inset()->getCursorPos(cur, xo, yo);
1204                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1205                 // '<=' in order to take the last possible position
1206                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1207                 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1208                 if (d <= best_dist) {
1209                         best_dist = d;
1210                         setCursor(it, false);
1211                 }
1212                 if (it == et)
1213                         break;
1214                 it.forwardPos();
1215         }
1216 }
1217
1218
1219 CursorSlice LCursor::normalAnchor()
1220 {
1221         if (anchor_.size() < depth()) {
1222                 resetAnchor();
1223                 lyxerr << "unusual Anchor size" << endl;
1224         }
1225         //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1226         // use Anchor on the same level as Cursor
1227         CursorSlice normal = anchor_[size() - 1];
1228 #if 0
1229         if (depth() < anchor_.size() && !(normal < xx())) {
1230                 // anchor is behind cursor -> move anchor behind the inset
1231                 ++normal.pos_;
1232         }
1233 #endif
1234         return normal;
1235 }
1236
1237
1238 /*
1239 DispatchResult dispatch(LCursor & cur, FuncRequest const & cmd)
1240 {
1241         // mouse clicks are somewhat special
1242         // check
1243         switch (cmd.action) {
1244         case LFUN_MOUSE_PRESS:
1245         case LFUN_MOUSE_MOTION:
1246         case LFUN_MOUSE_RELEASE:
1247         case LFUN_MOUSE_DOUBLE: {
1248                 CursorSlice & pos = back();
1249                 int x = 0;
1250                 int y = 0;
1251                 getPos(x, y);
1252                 if (x < cmd.x && pos() != 0) {
1253                         DispatchResult const res = prevAtom().nucleus()->dispatch(cmd);
1254                         if (res.dispatched())
1255                                 return res;
1256                 }
1257                 if (x > cmd.x && pos() != lastpos()) {
1258                         DispatchResult const res = inset()->dispatch(cmd);
1259                         if (res.dispatched())
1260                                 return res;
1261                 }
1262         }
1263         default:
1264         break;
1265         }
1266 }
1267 */
1268
1269
1270 void LCursor::handleFont(string const & font)
1271 {
1272         lyxerr << "LCursor::handleFont: " << font << endl;
1273         string safe;
1274         if (selection()) {
1275                 macroModeClose();
1276                 safe = grabAndEraseSelection();
1277         }
1278
1279         if (lastpos() != 0) {
1280                 // something left in the cell
1281                 if (pos() == 0) {
1282                         // cursor in first position
1283                         popLeft();
1284                 } else if (pos() == lastpos()) {
1285                         // cursor in last position
1286                         popRight();
1287                 } else {
1288                         // cursor in between. split cell
1289                         MathArray::iterator bt = cell().begin();
1290                         MathAtom at = createMathInset(font);
1291                         at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1292                         cell().erase(bt, bt + pos());
1293                         popLeft();
1294                         plainInsert(at);
1295                 }
1296         } else {
1297                 // nothing left in the cell
1298                 pullArg();
1299                 plainErase();
1300         }
1301         insert(safe);
1302 }
1303
1304
1305 void LCursor::message(string const & msg) const
1306 {
1307         bv().owner()->getLyXFunc().setMessage(msg);
1308 }
1309
1310
1311 void LCursor::errorMessage(string const & msg) const
1312 {
1313         bv().owner()->getLyXFunc().setErrorMessage(msg);
1314 }
1315
1316
1317 string LCursor::selectionAsString(bool label) const
1318 {
1319         if (!selection())
1320                 return string();
1321
1322         if (inTexted()) {
1323                 Buffer const & buffer = *bv().buffer();
1324
1325                 // should be const ...
1326                 ParagraphList::iterator startpit = text()->getPar(selBegin());
1327                 ParagraphList::iterator endpit = text()->getPar(selEnd());
1328                 size_t const startpos = selBegin().pos();
1329                 size_t const endpos = selEnd().pos();
1330
1331                 if (startpit == endpit)
1332                         return startpit->asString(buffer, startpos, endpos, label);
1333
1334                 // First paragraph in selection
1335                 string result =
1336                         startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1337
1338                 // The paragraphs in between (if any)
1339                 ParagraphList::iterator pit = startpit;
1340                 for (++pit; pit != endpit; ++pit)
1341                         result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1342
1343                 // Last paragraph in selection
1344                 result += endpit->asString(buffer, 0, endpos, label);
1345
1346                 return result;
1347         }
1348
1349 #warning an mathed?
1350         return string();
1351 }
1352
1353
1354 string LCursor::currentState()
1355 {
1356         if (inMathed()) {
1357                 std::ostringstream os;
1358                 info(os);
1359                 return os.str();
1360         }
1361         return text() ? text()->currentState(*this) : string();
1362 }
1363
1364
1365 // only used by the spellchecker
1366 void LCursor::replaceWord(string const & replacestring)
1367 {
1368         LyXText * t = text();
1369         BOOST_ASSERT(t);
1370
1371         t->replaceSelectionWithString(*this, replacestring);
1372         t->setSelectionRange(*this, replacestring.length());
1373
1374         // Go back so that replacement string is also spellchecked
1375         for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
1376                 t->cursorLeft(*this);
1377 }
1378
1379
1380 void LCursor::update()
1381 {
1382         bv().update();
1383 }
1384
1385
1386 string LCursor::getPossibleLabel()
1387 {
1388         return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1389 }
1390
1391
1392 void LCursor::undispatched()
1393 {
1394         disp_.dispatched(false);
1395 }
1396
1397
1398 void LCursor::dispatched(dispatch_result_t res)
1399 {
1400         disp_.val(res);
1401 }
1402
1403
1404 void LCursor::noUpdate()
1405 {
1406         disp_.update(false);
1407 }
1408
1409
1410 void LCursor::noPop()
1411 {
1412         nopop_ = true;
1413 }