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