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