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