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