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