]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
fix bug that disabled entering 'special char macros' like \, and \:
[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         MathInset::difference_type const t = macroNamePos();
638         if (t == -1)
639                 return;
640         string s = macroName();
641         array().erase(t, pos());
642         pos() = t;
643         if (s != "\\")
644                 interpret(s);
645 }
646
647
648 MathInset::difference_type MathCursor::macroNamePos() const
649 {
650         for (MathInset::difference_type i = pos() - 1; i >= 0; --i) {
651                 MathAtom & p = array().at(i);
652                 if (p->code() == LM_TC_TEX && p->getChar() == '\\')
653                         return i;
654         }
655         return -1;
656 }
657
658
659 string MathCursor::macroName() const
660 {
661         string s;
662         MathInset::difference_type i = macroNamePos();
663         for (; i >= 0 && i < int(pos()); ++i)
664                 s += array().at(i)->getChar();
665         return s;
666 }
667
668
669 void MathCursor::selCopy()
670 {
671         dump("selCopy");
672         if (selection_) {
673                 theSelection.grab(*this);
674                 selClear();
675         }
676 }
677
678
679 void MathCursor::selCut()
680 {
681         dump("selCut");
682         if (selection_) {
683                 theSelection.grab(*this);
684                 theSelection.erase(*this);
685                 selClear();
686         } else {
687                 theSelection.clear();
688         }
689 }
690
691
692 void MathCursor::selDel()
693 {
694         dump("selDel");
695         if (selection_) {
696                 theSelection.erase(*this);
697                 if (pos() > size())
698                         pos() = size();
699                 selClear();
700         }
701 }
702
703
704 void MathCursor::selPaste()
705 {
706         dump("selPaste");
707         theSelection.paste(*this);
708         //theSelection.grab(*this);
709         //selClear();
710 }
711
712
713 void MathCursor::selHandle(bool sel)
714 {
715         if (sel == selection_)
716                 return;
717         //theSelection.clear();
718         Anchor_    = Cursor_;
719         selection_ = sel;
720 }
721
722
723 void MathCursor::selStart()
724 {
725         dump("selStart 1");
726         //theSelection.clear();
727         Anchor_ = Cursor_;
728         selection_ = true;
729         dump("selStart 2");
730 }
731
732
733 void MathCursor::selClear()
734 {
735         dump("selClear 1");
736         selection_ = false;
737         dump("selClear 2");
738 }
739
740
741 void MathCursor::selGet(MathArray & ar)
742 {
743         dump("selGet");
744         if (!selection_)
745                 return;
746
747         theSelection.grab(*this);
748         ar = theSelection.glue();
749 }
750
751
752
753 void MathCursor::drawSelection(Painter & pain) const
754 {
755         if (!selection_)
756                 return;
757
758         MathCursorPos i1;
759         MathCursorPos i2;
760         getSelection(i1, i2);
761
762         if (i1.idx_ == i2.idx_) {
763                 MathXArray & c = i1.xcell();
764                 int x1 = c.xo() + c.pos2x(i1.pos_);
765                 int y1 = c.yo() - c.ascent();
766                 int x2 = c.xo() + c.pos2x(i2.pos_);
767                 int y2 = c.yo() + c.descent();
768                 pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
769         } else {
770                 vector<MathInset::idx_type> indices
771                         = i1.par_->idxBetween(i1.idx_, i2.idx_);
772                 for (unsigned i = 0; i < indices.size(); ++i) {
773                         MathXArray & c = i1.xcell(indices[i]);
774                         int x1 = c.xo();
775                         int y1 = c.yo() - c.ascent();
776                         int x2 = c.xo() + c.width();
777                         int y2 = c.yo() + c.descent();
778                         pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
779                 }
780         }
781
782 #if 0
783         // draw anchor if different from selection boundary
784         MathCursorPos anc = Anchor_.back();
785         if (anc != i1 && anc != i2) {
786                 MathXArray & c = anc.xcell();
787                 int x  = c.xo() + c.pos2x(anc.pos_);
788                 int y1 = c.yo() - c.ascent();
789                 int y2 = c.yo() + c.descent();
790                 pain.line(x, y1, x, y2, LColor::math);
791         }
792 #endif
793 }
794
795
796 void MathCursor::handleFont(MathTextCodes t)
797 {
798         macroModeClose();
799         if (selection_) {
800                 MathCursorPos i1;
801                 MathCursorPos i2;
802                 getSelection(i1, i2);
803                 if (i1.idx_ == i2.idx_) {
804                         MathArray & ar = i1.cell();
805                         for (MathInset::pos_type pos = i1.pos_; pos != i2.pos_; ++pos)
806                                 ar.at(pos)->handleFont(t);
807                 }
808         } else
809                 lastcode_ = (lastcode_ == t) ? LM_TC_VAR : t;
810 }
811
812
813 void MathCursor::handleDelim(string const & l, string const & r)
814 {
815         handleNest(new MathDelimInset(l, r));
816 }
817
818
819 void MathCursor::handleNest(MathInset * p)
820 {
821         if (selection_) {
822                 selCut();
823                 p->cell(0) = theSelection.glue();
824         }
825         insert(MathAtom(p)); // this invalidates p!
826         pushRight(prevAtom());
827 }
828
829
830 void MathCursor::getPos(int & x, int & y)
831 {
832 #ifdef WITH_WARNINGS
833 #warning This should probably take cellXOffset and cellYOffset into account
834 #endif
835         x = xarray().xo() + xarray().pos2x(pos());
836         y = xarray().yo();
837 }
838
839
840 MathInset * MathCursor::par() const
841 {
842         return cursor().par_;
843 }
844
845
846 InsetFormulaBase * MathCursor::formula()
847 {
848         return formula_;
849 }
850
851
852 MathCursor::idx_type MathCursor::idx() const
853 {
854         return cursor().idx_;
855 }
856
857
858 MathCursor::idx_type & MathCursor::idx()
859 {
860         return cursor().idx_;
861 }
862
863
864 MathCursor::pos_type MathCursor::pos() const
865 {
866         return cursor().pos_;
867 }
868
869
870 MathCursor::pos_type & MathCursor::pos()
871 {
872         return cursor().pos_;
873 }
874
875
876 bool MathCursor::inMacroMode() const
877 {
878         return macroNamePos() != -1;
879 }
880
881
882 bool MathCursor::inMacroArgMode() const
883 {
884         return pos() > 0 && prevAtom()->getChar() == '#';
885 }
886
887
888 bool MathCursor::selection() const
889 {
890         return selection_;
891 }
892
893
894 MathGridInset * MathCursor::enclosingGrid(MathCursor::idx_type & idx) const
895 {
896         for (MathInset::difference_type i = Cursor_.size() - 1; i >= 0; --i) {
897                 MathGridInset * p = Cursor_[i].par_->asGridInset();
898                 if (p) {
899                         idx = Cursor_[i].idx_;
900                         return p;
901                         lyxerr << "found grid and idx: " << idx << "\n";
902                 }
903         }
904         return 0;
905 }
906
907
908 void MathCursor::popToEnclosingGrid()
909 {
910         while (Cursor_.size() && !Cursor_.back().par_->asGridInset())
911                 Cursor_.pop_back();
912 }
913
914
915 void MathCursor::pullArg(bool goright)
916 {
917         dump("pullarg");
918         MathArray a = array();
919
920         MathScriptInset const * p = par()->asScriptInset();
921         if (p) {
922                 // special handling for scripts
923                 const bool up = p->hasUp();
924                 popLeft();
925                 MathScriptInset * q = nextAtom()->asScriptInset();
926                 if (q)
927                         q->removeScript(up);
928                 ++pos();
929                 array().insert(pos(), a);
930                 return;
931         }
932
933         if (popLeft()) {
934                 plainErase();
935                 array().insert(pos(), a);
936                 if (goright)
937                         pos() += a.size();
938         } else {
939                 formula()->mutateToText();
940         }
941 }
942
943
944 void MathCursor::touch()
945 {
946         cursor_type::const_iterator it = Cursor_.begin();
947         cursor_type::const_iterator et = Cursor_.end();
948         for ( ; it != et; ++it)
949                 it->xcell().touch();
950 }
951
952
953 void MathCursor::normalize()
954 {
955 #if 0
956         // rebreak
957         {
958                 MathIterator it = ibegin(formula()->par().nucleus());
959                 MathIterator et = iend(formula()->par().nucleus());
960                 for (; it != et; ++it)
961                         if (it.par()->asBoxInset())
962                                 it.par()->asBoxInset()->rebreak();
963         }
964 #endif
965
966         if (idx() >= par()->nargs()) {
967                 lyxerr << "this should not really happen - 1: "
968                        << idx() << " " << par()->nargs() << "\n";
969                 dump("error 2");
970         }
971         idx() = min(idx(), par()->nargs() - 1);
972
973         if (pos() > size()) {
974                 lyxerr << "this should not really happen - 2: "
975                         << pos() << " " << size() <<  " in idx: " << idx()
976                         << " in atom: '";
977                 WriteStream wi(lyxerr, false, true);
978                 par()->write(wi);
979                 lyxerr << "\n";
980                 dump("error 4");
981         }
982         pos() = min(pos(), size());
983
984         // remove empty scripts if possible
985         for (pos_type i = 0; i < size(); ++i) {
986                 MathScriptInset * p = array().at(i)->asScriptInset();
987                 if (p) {
988                         p->removeEmptyScripts();
989                         if (p->empty())
990                                 array().erase(i);
991                 }
992         }
993
994         // fix again position
995         pos() = min(pos(), size());
996 }
997
998
999 MathCursor::size_type MathCursor::size() const
1000 {
1001         return array().size();
1002 }
1003
1004
1005 MathCursor::col_type MathCursor::hullCol() const
1006 {
1007         return Cursor_[0].par_->asGridInset()->col(Cursor_[0].idx_);
1008 }
1009
1010
1011 MathCursor::row_type MathCursor::hullRow() const
1012 {
1013         return Cursor_[0].par_->asGridInset()->row(Cursor_[0].idx_);
1014 }
1015
1016
1017 bool MathCursor::hasPrevAtom() const
1018 {
1019         return pos() > 0;
1020 }
1021
1022
1023 bool MathCursor::hasNextAtom() const
1024 {
1025         return pos() < size();
1026 }
1027
1028
1029 MathAtom const & MathCursor::prevAtom() const
1030 {
1031         lyx::Assert(pos() > 0);
1032         return array().at(pos() - 1);
1033 }
1034
1035
1036 MathAtom & MathCursor::prevAtom()
1037 {
1038         lyx::Assert(pos() > 0);
1039         return array().at(pos() - 1);
1040 }
1041
1042
1043 MathAtom const & MathCursor::nextAtom() const
1044 {
1045         lyx::Assert(pos() < size());
1046         return array().at(pos());
1047 }
1048
1049
1050 MathAtom & MathCursor::nextAtom()
1051 {
1052         lyx::Assert(pos() < size());
1053         return array().at(pos());
1054 }
1055
1056
1057 MathArray & MathCursor::array() const
1058 {
1059         static MathArray dummy;
1060
1061         if (idx() >= par()->nargs()) {
1062                 lyxerr << "############  idx_ " << idx() << " not valid\n";
1063                 return dummy;
1064         }
1065
1066         if (Cursor_.size() == 0) {
1067                 lyxerr << "############  Cursor_.size() == 0 not valid\n";
1068                 return dummy;
1069         }
1070
1071         return cursor().cell();
1072 }
1073
1074
1075 MathXArray & MathCursor::xarray() const
1076 {
1077         static MathXArray dummy;
1078
1079         if (Cursor_.size() == 0) {
1080                 lyxerr << "############  Cursor_.size() == 0 not valid\n";
1081                 return dummy;
1082         }
1083
1084         return cursor().xcell();
1085 }
1086
1087
1088 void MathCursor::idxNext()
1089 {
1090         par()->idxNext(idx(), pos());
1091 }
1092
1093
1094 void MathCursor::idxPrev()
1095 {
1096         par()->idxPrev(idx(), pos());
1097 }
1098
1099
1100 void MathCursor::splitCell()
1101 {
1102         if (idx() + 1 == par()->nargs())
1103                 return;
1104         MathArray ar = array();
1105         ar.erase(0, pos());
1106         array().erase(pos(), size());
1107         ++idx();
1108         pos() = 0;
1109         array().insert(0, ar);
1110 }
1111
1112
1113 void MathCursor::breakLine()
1114 {
1115         // leave inner cells
1116         while (popRight())
1117                 ;
1118
1119         MathHullInset * p = formula()->par()->asHullInset();
1120         if (!p)
1121                 return;
1122
1123         if (p->getType() == LM_OT_SIMPLE || p->getType() == LM_OT_EQUATION) {
1124                 p->mutate(LM_OT_EQNARRAY);
1125                 idx() = 0;
1126                 pos() = size();
1127         } else {
1128                 p->addRow(hullRow());
1129
1130                 // split line
1131                 const row_type r = hullRow();
1132                 for (col_type c = hullCol() + 1; c < p->ncols(); ++c)
1133                         p->cell(p->index(r, c)).swap(p->cell(p->index(r + 1, c)));
1134
1135                 // split cell
1136                 splitCell();
1137                 p->cell(idx()).swap(p->cell(idx() + p->ncols() - 1));
1138         }
1139 }
1140
1141
1142 //void MathCursor::readLine(MathArray & ar) const
1143 //{
1144 //      idx_type base = row() * par()->ncols();
1145 //      for (idx_type off = 0; off < par()->ncols(); ++off)
1146 //              ar.push_back(par()->cell(base + off));
1147 //}
1148
1149
1150 char MathCursor::valign() const
1151 {
1152         idx_type idx;
1153         MathGridInset * p = enclosingGrid(idx);
1154         return p ? p->valign() : '\0';
1155 }
1156
1157
1158 char MathCursor::halign() const
1159 {
1160         idx_type idx;
1161         MathGridInset * p = enclosingGrid(idx);
1162         return p ? p->halign(idx % p->ncols()) : '\0';
1163 }
1164
1165
1166 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1167 {
1168         MathCursorPos anc = normalAnchor();
1169         if (anc < cursor()) {
1170                 i1 = anc;
1171                 i2 = cursor();
1172         } else {
1173                 i1 = cursor();
1174                 i2 = anc;
1175         }
1176 }
1177
1178
1179 MathCursorPos & MathCursor::cursor()
1180 {
1181         lyx::Assert(Cursor_.size());
1182         return Cursor_.back();
1183 }
1184
1185
1186 MathCursorPos const & MathCursor::cursor() const
1187 {
1188         lyx::Assert(Cursor_.size());
1189         return Cursor_.back();
1190 }
1191
1192
1193 bool MathCursor::goUpDown(bool up)
1194 {
1195         // Be warned: The 'logic' implemented in this function is highly fragile.
1196         // A distance of one pixel or a '<' vs '<=' _really_ matters.
1197         // So fiddle around with it only if you know what you are doing!
1198         int xlow, xhigh, ylow, yhigh;
1199
1200   int xo, yo;
1201         getPos(xo, yo);
1202
1203         // try neigbouring script insets
1204         // try left
1205         if (hasPrevAtom()) {
1206                 MathScriptInset * p = prevAtom()->asScriptInset();
1207                 if (p && p->has(up)) {
1208                         --pos();
1209                         push(nextAtom());
1210                         idx() = up; // the superscript has index 1
1211                         pos() = size();
1212                         ///lyxerr << "updown: handled by scriptinset to the left\n";
1213                         return true;
1214                 }
1215         }
1216
1217         // try right
1218         if (hasNextAtom()) {
1219                 MathScriptInset * p = nextAtom()->asScriptInset();
1220                 if (p && p->has(up)) {
1221                         push(nextAtom());
1222                         idx() = up;
1223                         pos() = 0;
1224                         ///lyxerr << "updown: handled by scriptinset to the right\n";
1225                         return true;
1226                 }
1227         }
1228
1229         // try current cell
1230         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1231         //if (up)
1232         //      yhigh = yo - 4;
1233         //else
1234         //      ylow = yo + 4;
1235         //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1236         //      lyxerr << "updown: handled by brute find in the same cell\n";
1237         //      return true;
1238         //}
1239
1240         // try to find an inset that knows better then we
1241         while (1) {
1242                 ///lyxerr << "updown: We are in " << *par() << " idx: " << idx() << '\n';
1243                 // ask inset first
1244                 if (par()->idxUpDown(idx(), up)) {
1245                         // we found a cell that thinks it has something "below" us.
1246                         ///lyxerr << "updown: found inset that handles UpDown\n";
1247                         xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1248                         // project (xo,yo) onto proper box
1249                         ///lyxerr << "\n   xo: " << xo << " yo: " << yo
1250                         ///       << "\n   xlow: " << xlow << " ylow: " << ylow
1251                         ///       << "\n   xhigh: " << xhigh << " yhigh: " << yhigh;
1252                         xo = min(max(xo, xlow), xhigh);
1253                         yo = min(max(yo, ylow), yhigh);
1254                         ///lyxerr << "\n   xo2: " << xo << " yo2: " << yo << "\n";
1255                         bruteFind(xo, yo, xlow, xhigh, ylow, yhigh);
1256                         ///lyxerr << "updown: handled by final brute find\n";
1257                         return true;
1258                 }
1259
1260                 // leave inset
1261                 if (!popLeft()) {
1262                         // no such inset found, just take something "above"
1263                         ///lyxerr << "updown: handled by strange case\n";
1264                         return
1265                                 bruteFind(xo, yo,
1266                                         formula()->xlow(),
1267                                         formula()->xhigh(),
1268                                         up ? formula()->ylow() : yo + 4,
1269                                         up ? yo - 4 : formula()->yhigh()
1270                                 );
1271                 }
1272                 
1273                 // any improvement so far?
1274                 int xnew, ynew;
1275                 getPos(xnew, ynew);
1276                 if (up ? ynew < yo : ynew > yo)
1277                         return true;
1278         }
1279 }
1280
1281
1282 bool MathCursor::bruteFind
1283         (int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1284 {
1285         cursor_type best_cursor;
1286         double best_dist = 1e10;
1287
1288         MathIterator it = ibegin(formula()->par().nucleus());
1289         MathIterator et = iend(formula()->par().nucleus());
1290         while (1) {
1291                 // avoid invalid nesting when selecting
1292                 if (!selection_ || positionable(it.cursor(), Anchor_)) {
1293                         MathCursorPos const & top = it.position();
1294                         int xo = top.xpos();
1295                         int yo = top.ypos();
1296                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1297                                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1298                                 // '<=' in order to take the last possible position
1299                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1300                                 if (d <= best_dist) {
1301                                         best_dist   = d;
1302                                         best_cursor = it.cursor();
1303                                 }
1304                         }
1305                 }
1306
1307                 if (it == et)
1308                         break;
1309                 ++it;
1310         }
1311
1312         if (best_dist < 1e10)
1313                 Cursor_ = best_cursor;
1314         return best_dist < 1e10;
1315 }
1316
1317
1318 bool MathCursor::idxLeft()
1319 {
1320         return par()->idxLeft(idx(), pos());
1321 }
1322
1323
1324 bool MathCursor::idxRight()
1325 {
1326         return par()->idxRight(idx(), pos());
1327 }
1328
1329
1330 bool MathCursor::interpret(string const & s)
1331 {
1332         //lyxerr << "interpret 1: '" << s << "'\n";
1333         if (s.empty())
1334                 return true;
1335
1336         //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
1337         //owner_->getIntl()->getTrans().TranslateAndInsert(s[0], lt);
1338         //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
1339
1340         if (s.size() >= 5 && s.substr(0, 5) == "cases") {
1341                 unsigned int n = 1;
1342                 istringstream is(s.substr(5).c_str());
1343                 is >> n;
1344                 n = max(1u, n);
1345                 niceInsert(MathAtom(new MathCasesInset(n)));
1346                 return true;
1347         }
1348
1349         if (s.size() >= 6 && s.substr(0, 6) == "matrix") {
1350                 unsigned int m = 1;
1351                 unsigned int n = 1;
1352                 string v_align;
1353                 string h_align;
1354                 istringstream is(s.substr(6).c_str());
1355                 is >> m >> n >> v_align >> h_align;
1356                 m = max(1u, m);
1357                 n = max(1u, n);
1358                 v_align += 'c';
1359                 niceInsert(MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
1360                 return true;
1361         }
1362
1363         if (s.size() >= 7 && s.substr(0, 7) == "replace") {
1364                 ReplaceData rep;
1365                 istringstream is(s.substr(7).c_str());
1366                 string from, to;
1367                 is >> from >> to;
1368                 mathed_parse_cell(rep.from, from);
1369                 mathed_parse_cell(rep.to, to);
1370                 lyxerr << "replacing '" << from << "' with '" << to << "'\n";
1371                 par()->replace(rep);
1372                 return true;
1373         }
1374
1375         string name = s.substr(1);
1376
1377         if (name == "over" || name == "choose" || name == "atop") {
1378                 MathArray ar = array();
1379                 MathAtom t(createMathInset(name));
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(name);
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() == name)
1397         {
1398                 lyxerr << "can't enter recursive macro\n";
1399                 return true;
1400         }
1401
1402         niceInsert(createMathInset(name));
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         //lyxerr << "interpret 2: '" << c << "'\n";
1437         if (inMacroArgMode()) {
1438                 --pos();
1439                 plainErase();
1440                 int n = c - '0';
1441                 MathMacroTemplate * p = formula()->par()->asMacroTemplate();
1442                 if (p && 1 <= n && n <= p->numargs())
1443                         insert(MathAtom(new MathMacroArgument(c - '0', lastcode_)));
1444                 else {
1445                         insert(MathAtom(new MathSpecialCharInset('#')));
1446                         interpret(c); // try again
1447                 }
1448                 return true;
1449         }
1450
1451         // handle macroMode
1452         if (inMacroMode()) {
1453                 string name = macroName();
1454                 //lyxerr << "interpret name: '" << name << "'\n";
1455
1456                 // extend macro name if possible
1457                 if (isalpha(c)) {
1458                         insert(c, LM_TC_TEX);
1459                         return true;
1460                 }
1461
1462                 // leave macro mode if explicitly requested
1463                 if (c == ' ') {
1464                         macroModeClose();
1465                         return true;
1466                 }
1467
1468                 // handle 'special char' macros
1469                 if (name == "\\") {
1470                         // remove the '\\'
1471                         backspace();
1472                         if (c == '\\') 
1473                                 interpret("\\backslash");
1474                         else
1475                                 interpret(string("\\") + c);
1476                         return true;
1477                 }
1478
1479                 // leave macro mode and try again
1480                 macroModeClose();
1481                 interpret(c);
1482                 return true;
1483         }
1484
1485         if (selection_) {
1486                 selClear();
1487                 if (c == ' ')
1488                         return true;
1489                 // fall through in the other cases
1490         }
1491
1492         if (lastcode_ == LM_TC_TEXTRM || par()->asBoxInset()) {
1493                 // suppress direct insertion of two spaces in a row
1494                 // the still allows typing  '<space>a<space>' and deleting the 'a', but
1495                 // it is better than nothing...
1496                 if (c == ' ' && hasPrevAtom() && prevAtom()->getChar() == ' ')
1497                         return true;
1498                 insert(c, LM_TC_TEXTRM);
1499                 return true;
1500         }
1501
1502         if (c == ' ') {
1503                 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1504                         prevAtom()->asSpaceInset()->incSpace();
1505                         return true;
1506                 }
1507                 if (popRight())
1508                         return true;
1509                 // if are at the very end, leave the formula
1510                 return pos() != size();
1511         }
1512
1513         if (c == '#') {
1514                 insert(c, LM_TC_TEX);
1515                 return true;
1516         }
1517
1518 /*
1519         if (c == '{' || c == '}', c)) {
1520                 insert(c, LM_TC_TEX);
1521                 return true;
1522         }
1523 */
1524
1525         if (c == '{') {
1526                 niceInsert(MathAtom(new MathBraceInset));
1527                 return true;
1528         }
1529
1530         if (c == '}') {
1531                 return true;
1532         }
1533
1534         if (c == '$' || c == '%') {
1535                 insert(MathAtom(new MathSpecialCharInset(c)));
1536                 lastcode_ = LM_TC_VAR;
1537                 return true;
1538         }
1539
1540         if (isalpha(c) && lastcode_ == LM_TC_GREEK) {
1541                 insert(c, LM_TC_VAR);
1542                 return true;
1543         }
1544
1545         if (isalpha(c) && lastcode_ == LM_TC_GREEK1) {
1546                 insert(c, LM_TC_VAR);
1547                 lastcode_ = LM_TC_VAR;
1548                 return true;
1549         }
1550
1551         if (c == '\\') {
1552                 insert(c, LM_TC_TEX);
1553                 //bv->owner()->message(_("TeX mode"));
1554                 return true;
1555         }
1556
1557         // no special circumstances, so insert the character without any fuss
1558         insert(c, lastcode_ == LM_TC_MIN ? MathCharInset::nativeCode(c) : lastcode_);
1559         lastcode_ = LM_TC_MIN;
1560         return true;
1561 }
1562
1563
1564
1565 MathCursorPos MathCursor::normalAnchor() const
1566 {
1567         if (Anchor_.size() < Cursor_.size()) {
1568                 Anchor_ = Cursor_;
1569                 lyxerr << "unusual Anchor size\n";
1570                 dump("1");
1571         }
1572         //lyx::Assert(Anchor_.size() >= Cursor_.size());
1573         // use Anchor on the same level as Cursor
1574         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1575         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1576                 // anchor is behind cursor -> move anchor behind the inset
1577                 ++normal.pos_;
1578         }
1579         return normal;
1580 }
1581
1582
1583 void MathCursor::stripFromLastEqualSign()
1584 {
1585         // find position of last '=' in the array
1586         MathArray & ar = cursor().cell();
1587         MathArray::const_iterator et = ar.end();
1588         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
1589                 if ((*it)->getChar() == '=')
1590                         et = it;
1591
1592         // delete everything behind this position
1593         ar.erase(et - ar.begin(), ar.size());
1594         pos() = ar.size();
1595 }
1596
1597
1598 void MathCursor::setSelection(cursor_type const & where, size_type n)
1599 {
1600         selection_ = true;
1601         Anchor_ = where;
1602         Cursor_ = where;
1603         cursor().pos_ += n;
1604 }
1605
1606
1607 string MathCursor::info() const
1608 {
1609         ostringstream os;
1610         if (pos() > 0)
1611                 prevAtom()->infoize(os);
1612         return os.str().c_str(); // .c_str() needed for lyxstring
1613 }