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