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