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