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