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