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