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