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