]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
ws cleanup
[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 neigbouring script insets
1184         // try left
1185         if (hasPrevAtom()) {
1186                 MathScriptInset * p = prevAtom()->asScriptInset();
1187                 if (p && p->has(up)) {
1188                         --pos();
1189                         push(nextAtom());
1190                         idx() = up; // the superscript has index 1
1191                         pos() = size();
1192                         ///lyxerr << "updown: handled by scriptinset to the left\n";
1193                         return true;
1194                 }
1195         }
1196
1197         // try right
1198         if (hasNextAtom()) {
1199                 MathScriptInset * p = nextAtom()->asScriptInset();
1200                 if (p && p->has(up)) {
1201                         push(nextAtom());
1202                         idx() = up;
1203                         pos() = 0;
1204                         ///lyxerr << "updown: handled by scriptinset to the right\n";
1205                         return true;
1206                 }
1207         }
1208
1209         // try current cell
1210         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1211         //if (up)
1212         //      yhigh = yo - 4;
1213         //else
1214         //      ylow = yo + 4;
1215         //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1216         //      lyxerr << "updown: handled by brute find in the same cell\n";
1217         //      return true;
1218         //}
1219
1220         // try to find an inset that knows better then we
1221         while (1) {
1222                 // we found a cell that thinks it has something "below" us.
1223                 if (par()->idxUpDown(idx(), up)) {
1224                         ///lyxerr << "updown: found inset that handles UpDown\n";
1225                         xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1226                         // project (xo,yo) onto proper box
1227                         ///lyxerr << "\n   xo: " << xo << " yo: " << yo
1228                         ///       << "\n   xlow: " << xlow << " ylow: " << ylow
1229                         ///       << "\n   xhigh: " << xhigh << " yhigh: " << yhigh;
1230                         xo = min(max(xo, xlow), xhigh);
1231                         yo = min(max(yo, ylow), yhigh);
1232                         ///lyxerr << "\n   xo2: " << xo << " yo2: " << yo << "\n";
1233                         bruteFind(xo, yo, xlow, xhigh, ylow, yhigh);
1234                         ///lyxerr << "updown: handled by final brute find\n";
1235                         return true;
1236                 }
1237
1238                 if (!popLeft()) {
1239                         // no such inset found, just take something "above"
1240                         ///lyxerr << "updown: handled by strange case\n";
1241                         return
1242                                 bruteFind(xo, yo,
1243                                         formula()->xlow(),
1244                                         formula()->xhigh(),
1245                                         up ? formula()->ylow() : yo + 4,
1246                                         up ? yo - 4 : formula()->yhigh()
1247                                 );
1248                 }
1249                 ///lyxerr << "updown: looping\n";
1250         }
1251 }
1252
1253
1254 bool MathCursor::bruteFind
1255         (int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1256 {
1257         cursor_type best_cursor;
1258         double best_dist = 1e10;
1259
1260         MathIterator it = ibegin(formula()->par().nucleus());
1261         MathIterator et = iend(formula()->par().nucleus());
1262         while (1) {
1263                 // avoid invalid nesting when selecting
1264                 if (!selection_ || positionable(it.cursor(), Anchor_)) {
1265                         MathCursorPos const & top = it.position();
1266                         int xo = top.xpos();
1267                         int yo = top.ypos();
1268                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1269                                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1270                                 if (d < best_dist) {
1271                                         best_dist   = d;
1272                                         best_cursor = it.cursor();
1273                                 }
1274                         }
1275                 }
1276
1277                 if (it == et)
1278                         break;
1279                 ++it;
1280         }
1281
1282         if (best_dist < 1e10)
1283                 Cursor_ = best_cursor;
1284         return best_dist < 1e10;
1285 }
1286
1287
1288 bool MathCursor::idxLeft()
1289 {
1290         return par()->idxLeft(idx(), pos());
1291 }
1292
1293
1294 bool MathCursor::idxRight()
1295 {
1296         return par()->idxRight(idx(), pos());
1297 }
1298
1299
1300 bool MathCursor::interpret(string const & s)
1301 {
1302         //lyxerr << "interpret 1: '" << s << "'\n";
1303         if (s.empty())
1304                 return true;
1305
1306         if (s.size() == 1)
1307                 return interpret(s[0]);
1308
1309         //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
1310         //owner_->getIntl()->getTrans().TranslateAndInsert(s[0], lt);
1311         //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
1312
1313         if (s.size() >= 5 && s.substr(0, 5) == "cases") {
1314                 unsigned int n = 1;
1315                 istringstream is(s.substr(5).c_str());
1316                 is >> n;
1317                 n = max(1u, n);
1318                 niceInsert(MathAtom(new MathCasesInset(n)));
1319                 return true;
1320         }
1321
1322         if (s.size() >= 6 && s.substr(0, 6) == "matrix") {
1323                 unsigned int m = 1;
1324                 unsigned int n = 1;
1325                 string v_align;
1326                 string h_align;
1327                 istringstream is(s.substr(6).c_str());
1328                 is >> m >> n >> v_align >> h_align;
1329                 m = max(1u, m);
1330                 n = max(1u, n);
1331                 v_align += 'c';
1332                 niceInsert(MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
1333                 return true;
1334         }
1335
1336         if (s.size() >= 7 && s.substr(0, 7) == "replace") {
1337                 ReplaceData rep;
1338                 istringstream is(s.substr(7).c_str());
1339                 string from, to;
1340                 is >> from >> to;
1341                 mathed_parse_cell(rep.from, from);
1342                 mathed_parse_cell(rep.to, to);
1343                 lyxerr << "replacing '" << from << "' with '" << to << "'\n";
1344                 par()->replace(rep);
1345                 return true;
1346         }
1347
1348         if (s == "\\over" || s == "\\choose" || s == "\\atop") {
1349                 MathArray ar = array();
1350                 MathAtom t(createMathInset(s.substr(1)));
1351                 t->asNestInset()->cell(0).swap(array());
1352                 pos() = 0;
1353                 niceInsert(t);
1354                 popRight();
1355                 left();
1356                 return true;
1357         }
1358
1359         latexkeys const * l = in_word_set(s.substr(1));
1360         if (l && (l->token == LM_TK_FONT || l->token == LM_TK_OLDFONT)) {
1361                 lastcode_ = static_cast<MathTextCodes>(l->id);
1362                 return true;
1363         }
1364
1365         // prevent entering of recursive macros
1366         if (formula()->lyxCode() == Inset::MATHMACRO_CODE
1367                 && formula()->getInsetName() == s.substr(1))
1368         {
1369                 lyxerr << "can't enter recursive macro\n";
1370                 return true;
1371         }
1372
1373         niceInsert(createMathInset(s.substr(1)));
1374         return true;
1375 }
1376
1377
1378 bool MathCursor::script(bool up)
1379 {
1380         macroModeClose();
1381         selCut();
1382         if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1383                 prevAtom()->asScriptInset()->ensure(up);
1384                 pushRight(prevAtom());
1385                 idx() = up;
1386                 pos() = size();
1387         } else if (hasNextAtom() && nextAtom()->asScriptInset()) {
1388                 nextAtom()->asScriptInset()->ensure(up);
1389                 pushLeft(nextAtom());
1390                 idx() = up;
1391                 pos() = 0;
1392         } else {
1393                 plainInsert(MathAtom(new MathScriptInset(up)));
1394                 prevAtom()->asScriptInset()->ensure(up);
1395                 pushRight(prevAtom());
1396                 idx() = up;
1397                 pos() = 0;
1398         }
1399         selPaste();
1400         dump("1");
1401         return true;
1402 }
1403
1404
1405 bool MathCursor::interpret(char c)
1406 {
1407         if (inMacroArgMode()) {
1408                 --pos();
1409                 plainErase();
1410                 int n = c - '0';
1411                 MathMacroTemplate * p = formula()->par()->asMacroTemplate();
1412                 if (p && 1 <= n && n <= p->numargs())
1413                         insert(MathAtom(new MathMacroArgument(c - '0', lastcode_)));
1414                 else {
1415                         insert(MathAtom(new MathSpecialCharInset('#')));
1416                         interpret(c); // try again
1417                 }
1418                 return true;
1419         }
1420
1421         // handle macroMode
1422         if (inMacroMode()) {
1423                 string name = macroName();
1424
1425                 if (name == "\\" && c == '\\') {
1426                         backspace();
1427                         interpret("\\backslash");
1428                         return true;
1429                 }
1430
1431                 if (isalpha(c)) {
1432                         insert(c, LM_TC_TEX);
1433                         return true;
1434                 }
1435
1436                 if (name == "\\") {
1437                         insert(c, LM_TC_TEX);
1438                         macroModeClose();
1439                         return true;
1440                 }
1441
1442                 macroModeClose();
1443
1444                 if (c == '\\')
1445                         insert(c, LM_TC_TEX);
1446                 else if (c != ' ')
1447                         insert(c, lastcode_);
1448
1449                 return true;
1450         }
1451
1452         if (selection_) {
1453                 selClear();
1454                 if (c == ' ')
1455                         return true;
1456                 // fall through in the other cases
1457         }
1458
1459         if (lastcode_ == LM_TC_TEXTRM || par()->asBoxInset()) {
1460                 // suppress direct insertion of two spaces in a row
1461                 // the still allows typing  '<space>a<space>' and deleting the 'a', but
1462                 // it is better than nothing...
1463                 if (c == ' ' && hasPrevAtom() && prevAtom()->getChar() == ' ')
1464                         return true;
1465                 insert(c, LM_TC_TEXTRM);
1466                 return true;
1467         }
1468
1469         if (c == ' ') {
1470                 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1471                         prevAtom()->asSpaceInset()->incSpace();
1472                         return true;
1473                 }
1474                 if (popRight())
1475                         return true;
1476                 // if are at the very end, leave the formula
1477                 return pos() != size();
1478         }
1479
1480         if (c == '#') {
1481                 insert(c, LM_TC_TEX);
1482                 return true;
1483         }
1484
1485 /*
1486         if (c == '{' || c == '}', c)) {
1487                 insert(c, LM_TC_TEX);
1488                 return true;
1489         }
1490 */
1491
1492         if (c == '{') {
1493                 niceInsert(MathAtom(new MathBraceInset));
1494                 return true;
1495         }
1496
1497         if (c == '}') {
1498                 return true;
1499         }
1500
1501         if (c == '$' || c == '%') {
1502                 insert(MathAtom(new MathSpecialCharInset(c)));
1503                 lastcode_ = LM_TC_VAR;
1504                 return true;
1505         }
1506
1507         if (isalpha(c) && lastcode_ == LM_TC_GREEK) {
1508                 insert(c, LM_TC_VAR);
1509                 return true;
1510         }
1511
1512         if (isalpha(c) && lastcode_ == LM_TC_GREEK1) {
1513                 insert(c, LM_TC_VAR);
1514                 lastcode_ = LM_TC_VAR;
1515                 return true;
1516         }
1517
1518         if (c == '\\') {
1519                 insert(c, LM_TC_TEX);
1520                 //bv->owner()->message(_("TeX mode"));
1521                 return true;
1522         }
1523
1524         // no special circumstances, so insert the character without any fuss
1525         insert(c, lastcode_ == LM_TC_MIN ? MathCharInset::nativeCode(c) : lastcode_);
1526         lastcode_ = LM_TC_MIN;
1527         return true;
1528 }
1529
1530
1531
1532 MathCursorPos MathCursor::normalAnchor() const
1533 {
1534         if (Anchor_.size() < Cursor_.size()) {
1535                 Anchor_ = Cursor_;
1536                 lyxerr << "unusual Anchor size\n";
1537                 dump("1");
1538         }
1539         //lyx::Assert(Anchor_.size() >= Cursor_.size());
1540         // use Anchor on the same level as Cursor
1541         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1542         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1543                 // anchor is behind cursor -> move anchor behind the inset
1544                 ++normal.pos_;
1545         }
1546         return normal;
1547 }
1548
1549
1550 void MathCursor::stripFromLastEqualSign()
1551 {
1552         // find position of last '=' in the array
1553         MathArray & ar = cursor().cell();
1554         MathArray::const_iterator et = ar.end();
1555         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
1556                 if ((*it)->getChar() == '=')
1557                         et = it;
1558
1559         // delete everything behind this position
1560         ar.erase(et - ar.begin(), ar.size());
1561         pos() = ar.size();
1562 }
1563
1564
1565 void MathCursor::setSelection(cursor_type const & where, size_type n)
1566 {
1567         selection_ = true;
1568         Anchor_ = where;
1569         Cursor_ = where;
1570         cursor().pos_ += n;
1571 }
1572
1573
1574 string MathCursor::info() const
1575 {
1576         ostringstream os;
1577         if (pos() > 0)
1578                 prevAtom()->infoize(os);
1579         return os.str();
1580 }