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