]> git.lyx.org Git - features.git/blob - src/mathed/math_cursor.C
5c4840ba13a9247178693e3b0226886994de14ce
[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                 // correct cursor position
1080                 --idx();
1081                 pos() = size();
1082         }
1083 }
1084
1085
1086 char MathCursor::valign() const
1087 {
1088         idx_type idx;
1089         MathArrayInset * p = enclosingArray(idx);
1090         return p ? p->valign() : '\0';
1091 }
1092
1093
1094 char MathCursor::halign() const
1095 {
1096         idx_type idx;
1097         MathArrayInset * p = enclosingArray(idx);
1098         return p ? p->halign(idx % p->ncols()) : '\0';
1099 }
1100
1101
1102 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1103 {
1104         MathCursorPos anc = normalAnchor();
1105         if (anc < cursor()) {
1106                 i1 = anc;
1107                 i2 = cursor();
1108         } else {
1109                 i1 = cursor();
1110                 i2 = anc;
1111         }
1112 }
1113
1114
1115 MathCursorPos & MathCursor::cursor()
1116 {
1117         return Cursor_.back();
1118 }
1119
1120
1121 MathCursorPos const & MathCursor::cursor() const
1122 {
1123         return Cursor_.back();
1124 }
1125
1126
1127 int MathCursor::cellXOffset() const
1128 {
1129         return par()->cellXOffset(idx());
1130 }
1131
1132
1133 int MathCursor::cellYOffset() const
1134 {
1135         return par()->cellYOffset(idx());
1136 }
1137
1138
1139 int MathCursor::xpos() const
1140 {
1141         return cellXOffset() + xarray().pos2x(pos());
1142 }
1143
1144
1145 int MathCursor::ypos() const
1146 {
1147         return cellYOffset();
1148 }
1149
1150
1151
1152 void MathCursor::gotoX(int x) 
1153 {
1154         pos() = xarray().x2pos(x - cellXOffset());
1155 }
1156
1157
1158 bool MathCursor::goUp()
1159 {
1160         // first ask the inset if it knows better then we
1161         if (par()->idxUp(idx(), pos()))
1162                 return true;
1163
1164         // leave subscript to the nearest side  
1165         MathScriptInset * p = par()->asScriptInset();
1166         if (p && idx() == 0) {
1167                 if (pos() <= size() / 2)
1168                         popLeft();
1169                 else
1170                         popRight();             
1171                 return true;
1172         }
1173
1174         // if not, apply brute force.
1175         int x0;
1176         int y0;
1177         getPos(x0, y0);
1178         std::vector<MathCursorPos> save = Cursor_;
1179         MathAtom const & out = formula()->par();
1180         y0 -= xarray().ascent();
1181         for (int y = y0 - 4; y > out->yo() - out->ascent(); y -= 4) {
1182                 setPos(x0, y);
1183                 if (save != Cursor_ && xarray().yo() < y0)
1184                         return true;    
1185         }
1186         Cursor_ = save;
1187         return false;
1188 }
1189
1190
1191 bool MathCursor::goDown()
1192 {
1193         // first ask the inset if it knows better then we
1194         if (par()->idxDown(idx(), pos()))
1195                 return true;
1196
1197         // leave superscript to the nearest side        
1198         MathScriptInset * p = par()->asScriptInset();
1199         if (p && idx() == 1) {
1200                 if (pos() <= size() / 2)
1201                         popLeft();
1202                 else
1203                         popRight();             
1204                 return true;
1205         }
1206
1207         // if not, apply brute force.
1208         int x0;
1209         int y0;
1210         getPos(x0, y0);
1211         std::vector<MathCursorPos> save = Cursor_;
1212         MathAtom const & out = formula()->par();
1213         y0 += xarray().descent();
1214         for (int y = y0 + 4; y < out->yo() + out->descent(); y += 4) {
1215                 setPos(x0, y);
1216                 if (save != Cursor_ && xarray().yo() > y0)
1217                         return true;    
1218         }
1219         Cursor_ = save;
1220         return false;
1221 }
1222
1223
1224 bool MathCursor::idxLeft()
1225 {
1226         return par()->idxLeft(idx(), pos());
1227 }
1228
1229
1230 bool MathCursor::idxRight()
1231 {
1232         return par()->idxRight(idx(), pos());
1233 }
1234
1235
1236 void MathCursor::interpret(string const & s)
1237 {
1238         //lyxerr << "interpret 1: '" << s << "'\n";
1239         //lyxerr << "in: " << in_word_set(s) << " \n";
1240
1241         if (s.empty())
1242                 return;
1243
1244         if (s.size() == 1) {
1245                 interpret(s[0]);
1246                 return;
1247         }
1248
1249         //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
1250         //owner_->getIntl()->getTrans().TranslateAndInsert(s[0], lt);   
1251         //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
1252
1253         if (s.size() > 7 && s.substr(0, 7) == "matrix ") {
1254                 unsigned int m = 1;
1255                 unsigned int n = 1;
1256                 string v_align;
1257                 string h_align;
1258                 istringstream is(s.substr(7).c_str());
1259                 is >> m >> n >> v_align >> h_align;
1260                 m = std::max(1u, m);
1261                 n = std::max(1u, n);
1262                 v_align += 'c';
1263                 niceInsert(MathAtom(new MathArrayInset(m, n, v_align[0], h_align)));
1264                 return;
1265         }
1266
1267         if (s == "\\over" || s == "\\choose" || s == "\\atop") {
1268                 MathArray ar = array();
1269                 MathAtom t = createMathInset(s.substr(1));
1270                 t->asNestInset()->cell(0).swap(array());
1271                 pos() = 0;
1272                 niceInsert(t);
1273                 popRight();
1274                 left();
1275                 return;
1276         }
1277
1278         niceInsert(createMathInset(s.substr(1)));
1279 }
1280
1281
1282 void MathCursor::interpret(char c)
1283 {
1284         //lyxerr << "interpret 2: '" << c << "'\n";
1285
1286         if (inMacroMode()) {
1287                 string name = macroName();
1288
1289                 if (name == "\\" && c == '#') {
1290                         insert(c, LM_TC_TEX);
1291                         return;
1292                 }
1293
1294                 if (name == "\\" && c == '\\') {
1295                         backspace();
1296                         interpret("\\backslash");
1297                         return;
1298                 }
1299
1300                 if (name == "\\#" && '1' <= c && c <= '9') {
1301                         insert(c, LM_TC_TEX);
1302                         macroModeClose();
1303                         return;
1304                 }
1305
1306                 if (isalpha(c)) {
1307                         insert(c, LM_TC_TEX);
1308                         return;
1309                 }
1310
1311                 if (name == "\\") {
1312                         insert(c, LM_TC_TEX);
1313                         macroModeClose();
1314                         return;
1315                 }
1316
1317                 macroModeClose();
1318                 return;
1319         }
1320
1321         // no macro mode
1322         if (c == '^' || c == '_') {
1323                 const bool up = (c == '^');
1324                 selCut();
1325                 if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1326                         prevAtom()->asScriptInset()->ensure(up);
1327                         pushRight(prevAtom());
1328                         idx() = up;
1329                         pos() = size();
1330                 } else if (hasNextAtom() && nextAtom()->asScriptInset()) {
1331                         nextAtom()->asScriptInset()->ensure(up);
1332                         pushLeft(nextAtom());
1333                         idx() = up;
1334                         pos() = 0;
1335                 } else {
1336                         plainInsert(MathAtom(new MathScriptInset(up)));
1337                         prevAtom()->asScriptInset()->ensure(up);
1338                         pushRight(prevAtom());
1339                         idx() = up;
1340                         pos() = 0;
1341                 }
1342                 selPaste();
1343                 dump("1");
1344                 return;
1345         }
1346
1347         if (selection_)
1348                 selDel();
1349
1350         if (lastcode_ == LM_TC_TEXTRM) {
1351                 insert(c, LM_TC_TEXTRM);
1352                 return;
1353         }
1354
1355         if (c == ' ') {
1356                 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1357                         prevAtom()->asSpaceInset()->incSpace();
1358                         return;
1359                 }
1360
1361                 if (mathcursor->popRight())
1362                         return;
1363
1364 #warning look here
1365                         // this would not work if the inset is in an table!
1366                         //bv->text->cursorRight(bv, true);
1367                         //result = FINISHED;
1368                 return;
1369         }
1370
1371         if (strchr("{}", c)) {
1372                 insert(c, LM_TC_TEX);
1373                 return;
1374         }
1375
1376         if (strchr("#$%", c)) {
1377                 insert(MathAtom(new MathSpecialCharInset(c)));  
1378                 lastcode_ = LM_TC_VAR;
1379                 return;
1380         }
1381
1382         if (isalpha(c) && (lastcode_ == LM_TC_GREEK || lastcode_ == LM_TC_GREEK1)) {
1383                 static char const greekl[][26] =
1384                         {"alpha", "beta", "chi", "delta", "epsilon", "phi",
1385                          "gamma", "eta", "iota", "epsilon", "kappa", "lambda", "mu",
1386                          "nu", "omega", "pi", "vartheta", "rho", "sigma",
1387                          "tau", "upsilon", "theta", "omega", "xi", "varphi", "zeta"};
1388                 static char const greeku[][26] =
1389                         {"alpha", "beta", "chi", "Delta", "varepsilon", "Phi",
1390                          "Gamma", "varepsilon", "varepsilon", "epsilon", "kappa", "Lambda", "mu",
1391                          "Nu", "Omega", "Pi", "vartheta", "varrho", "Sigma", "varsigma",
1392                          "Upsilon", "Theta", "Omega", "Xi", "Varphi", "zeta"};
1393         
1394                 latexkeys const * l = 0;        
1395                 if ('a' <= c && c <= 'z')
1396                         l = in_word_set(greekl[c - 'a']);
1397                 if ('A' <= c && c <= 'Z')
1398                         l = in_word_set(greeku[c - 'A']);
1399         
1400                 if (l)
1401                         insert(createMathInset(l));
1402                 else
1403                         insert(c, LM_TC_VAR);
1404
1405                 if (lastcode_ == LM_TC_GREEK1)
1406                         lastcode_ = LM_TC_VAR;
1407                 return; 
1408         }
1409
1410         if (c == '\\') {
1411                 insert(c, LM_TC_TEX);
1412                 //bv->owner()->message(_("TeX mode"));
1413                 return; 
1414         }
1415
1416         // no special circumstances, so insert the character without any fuss
1417         insert(c, LM_TC_MIN);
1418 }
1419
1420
1421
1422 ////////////////////////////////////////////////////////////////////////
1423
1424
1425 bool operator==(MathCursorPos const & ti, MathCursorPos const & it)
1426 {
1427         return ti.par_ == it.par_ && ti.idx_ == it.idx_ && ti.pos_ == it.pos_;
1428 }
1429
1430
1431 bool operator<(MathCursorPos const & ti, MathCursorPos const & it)
1432 {
1433         if (ti.par_ != it.par_) {
1434                 lyxerr << "can't compare cursor and anchor in different insets\n";
1435                 return true;
1436         }
1437         if (ti.idx_ != it.idx_)
1438                 return ti.idx_ < it.idx_;
1439         return ti.pos_ < it.pos_;
1440 }
1441
1442
1443 MathArray & MathCursorPos::cell(MathCursor::idx_type idx) const
1444 {
1445         return (*par_)->cell(idx);
1446 }
1447
1448
1449 MathArray & MathCursorPos::cell() const
1450 {
1451         return (*par_)->cell(idx_);
1452 }
1453
1454
1455 MathXArray & MathCursorPos::xcell(MathCursor::idx_type idx) const
1456 {
1457         return (*par_)->xcell(idx);
1458 }
1459
1460
1461 MathXArray & MathCursorPos::xcell() const
1462 {
1463         return (*par_)->xcell(idx_);
1464 }
1465
1466
1467 MathCursorPos MathCursor::normalAnchor() const
1468 {
1469         // use Anchor on the same level as Cursor
1470         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1471         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1472                 // anchor is behind cursor -> move anchor behind the inset
1473                 ++normal.pos_;
1474         }
1475         return normal;
1476 }
1477
1478