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