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