]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
8e70193a4dbe92dc9b422a714833855a73efc606
[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 (posLeft()) {
473                 plainErase();
474                 return;
475         }
476
477         if (size()) {
478                 pullArg(false);
479                 return;
480         }
481
482         erase();
483 }
484
485
486 void MathCursor::erase()
487 {
488         dump("erase 1");
489         if (inMacroMode())
490                 return;
491
492         if (selection_) {
493                 selDel();
494                 return;
495         }
496
497         // delete empty cells if necessary
498         if (pos() == 0 && array().empty()) {
499                 bool popit;
500                 bool removeit;
501                 par()->idxDelete(idx(), popit, removeit);
502                 if (popit && popLeft() && removeit)
503                         plainErase();
504                 return;
505         }
506
507         if (pos() < size())
508                 plainErase();
509
510         dump("erase 2");
511 }
512
513
514 void MathCursor::delLine()
515 {
516         macroModeClose();
517
518         if (selection_) {
519                 selDel();
520                 return;
521         }
522
523         if (par()->nrows() > 1)
524                 par()->delRow(row());
525 }
526
527
528 bool MathCursor::up(bool sel)
529 {
530         dump("up 1");
531         macroModeClose();
532         selHandle(sel);
533
534         if (selection_)
535                 return goUp();
536
537         // check whether we could move into a superscript on the right or on the left
538         if (prevAtom() && prevAtom()->up()) {
539                 pushRight(prevAtom()->up());            
540                 return true;
541         }
542
543         if (nextAtom() && nextAtom()->up()) {
544                 pushLeft(nextAtom()->up());             
545                 return true;
546         }
547
548         return goUp();
549 }
550
551
552 bool MathCursor::down(bool sel)
553 {
554         dump("down 1");
555         macroModeClose();
556         selHandle(sel);
557
558         if (selection_) 
559                 return goDown();
560
561         // check whether we could move into an subscript on the right or on the left
562         if (prevAtom() && prevAtom()->down()) {
563                 pushRight(prevAtom()->down());          
564                 return true;
565         }
566
567         if (nextAtom() && nextAtom()->down()) {
568                 pushLeft(nextAtom()->down());   
569                 return true;
570         }
571
572         return goDown();
573 }
574
575
576 bool MathCursor::toggleLimits()
577 {
578         MathAtom * t = prevAtom();
579         if (!t)
580                 return false;
581         int old = t->limits();
582         t->limits(old < 0 ? 1 : -1);
583         return old != t->limits();
584 }
585
586
587 void MathCursor::setSize(MathStyles size)
588 {
589         par()->userSetSize(size);
590 }
591
592
593 void MathCursor::macroModeClose()
594 {
595         string s = macroName();
596         if (s.size()) {
597                 pos() = pos() - s.size();
598                 for (unsigned i = 0; i < s.size(); ++i)
599                         plainErase();
600                 lastcode_ = LM_TC_VAR;
601                 interpret("\\" + s);
602         }
603 }
604
605
606 string MathCursor::macroName() const
607 {
608         string s;
609         for (int i = pos() - 1; i >= 0; --i) {
610                 MathInset * p = array().at(i)->nucleus();
611                 if (p && p->code() == LM_TC_TEX)
612                         s = p->getChar() + s;
613                 else
614                         break;
615         }
616         return s;
617 }
618
619
620 void MathCursor::selCopy()
621 {
622         seldump("selCopy");
623         if (selection_) {
624                 theSelection.grab(*this);
625                 selClear();
626         }
627 }
628
629
630 void MathCursor::selCut()
631 {
632         seldump("selCut");
633         if (selection_) {
634                 theSelection.grab(*this);
635                 theSelection.erase(*this);
636                 selClear();
637         } else {
638                 theSelection.clear();
639         }
640 }
641
642
643 void MathCursor::selDel()
644 {
645         seldump("selDel");
646         if (selection_) {
647                 theSelection.erase(*this);
648                 selClear();
649         }
650 }
651
652
653 void MathCursor::selPaste()
654 {
655         seldump("selPaste");
656         theSelection.paste(*this);
657         selClear();
658 }
659
660
661 void MathCursor::selHandle(bool sel)
662 {
663         if (sel == selection_)
664                 return;
665
666         theSelection.clear();
667         Anchor_    = Cursor_;
668         selection_ = sel;
669 }
670
671
672 void MathCursor::selStart()
673 {
674         seldump("selStart");
675         if (selection_)
676                 return;
677
678         theSelection.clear();
679         Anchor_ = Cursor_;
680         selection_ = true;
681 }
682
683
684 void MathCursor::selClear()
685 {
686         seldump("selClear");
687         selection_ = false;
688 }
689
690
691 void MathCursor::drawSelection(Painter & pain) const
692 {
693         if (!selection_)
694                 return;
695
696         MathCursorPos i1;
697         MathCursorPos i2;
698         getSelection(i1, i2);
699
700         //lyxerr << "selection from: " << i1 << " to " << i2 << "\n";
701
702         if (i1.idx_ == i2.idx_) {
703                 MathXArray & c = i1.xcell();
704                 int x1 = c.xo() + c.pos2x(i1.pos_);
705                 int y1 = c.yo() - c.ascent();
706                 int x2 = c.xo() + c.pos2x(i2.pos_);
707                 int y2 = c.yo() + c.descent();
708                 pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
709         } else {
710                 std::vector<int> indices = i1.par_->idxBetween(i1.idx_, i2.idx_);
711                 for (unsigned i = 0; i < indices.size(); ++i) {
712                         MathXArray & c = i1.xcell(indices[i]);
713                         int x1 = c.xo();
714                         int y1 = c.yo() - c.ascent();
715                         int x2 = c.xo() + c.width();
716                         int y2 = c.yo() + c.descent();
717                         pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
718                 }
719         }
720 }
721
722
723 MathTextCodes MathCursor::nextCode() const
724 {
725         //return (pos() == size()) ? LM_TC_VAR : nextInset()->code();
726         return LM_TC_VAR;
727 }
728
729
730 void MathCursor::handleFont(MathTextCodes t)
731 {
732         macroModeClose();
733         if (selection_) {
734                 MathCursorPos i1;
735                 MathCursorPos i2;
736                 getSelection(i1, i2); 
737                 if (i1.idx_ == i2.idx_) {
738                         MathArray & ar = i1.cell();
739                         for (int pos = i1.pos_; pos != i2.pos_; ++pos) {
740                                 MathInset * p = ar.at(pos)->nucleus();
741                                 if (p)
742                                         p->handleFont(t);
743                         }
744                 }
745         } else 
746                 lastcode_ = (lastcode_ == t) ? LM_TC_VAR : t;
747 }
748
749
750 void MathCursor::handleDelim(string const & l, string const & r)
751 {
752         handleNest(new MathDelimInset(l, r));
753 }
754
755
756 void MathCursor::handleNest(MathInset * p)
757 {
758         if (selection_) {
759                 selCut();
760                 p->cell(0) = theSelection.glue();
761         }
762         insert(p); // this invalidates p!
763         p = prevAtom()->nucleus();      
764         pushRight(p);
765 }
766
767
768 void MathCursor::getPos(int & x, int & y)
769 {
770 #ifdef WITH_WARNINGS
771 #warning This should probably take cellXOffset and cellYOffset into account
772 #endif
773         x = xarray().xo() + xarray().pos2x(pos());
774         y = xarray().yo();
775 }
776
777
778 MathInset * MathCursor::par() const
779 {
780         return cursor().par_;
781 }
782
783
784 InsetFormulaBase const * MathCursor::formula()
785 {
786         return formula_;
787 }
788
789
790 int MathCursor::idx() const
791 {
792         return cursor().idx_;
793 }
794
795
796 int & MathCursor::idx()
797 {
798         return cursor().idx_;
799 }
800
801
802 int MathCursor::pos() const
803 {
804         return cursor().pos_;
805 }
806
807
808 int & MathCursor::pos()
809 {
810         return cursor().pos_;
811 }
812
813
814 bool MathCursor::inMacroMode() const
815 {
816         return lastcode_ == LM_TC_TEX;
817 }
818
819
820 bool MathCursor::selection() const
821 {
822         return selection_;
823 }
824
825
826 MathArrayInset * MathCursor::enclosingArray(int & idx) const
827 {
828         for (int i = Cursor_.size() - 1; i >= 0; --i) {
829                 if (Cursor_[i].par_->isArray()) {
830                         idx = Cursor_[i].idx_;
831                         return static_cast<MathArrayInset *>(Cursor_[i].par_);
832                 }
833         }
834         return 0;
835 }
836
837
838 void MathCursor::pullArg(bool goright)
839 {
840         // pullArg
841         dump("pullarg");
842         MathArray a = array();
843         if (popLeft()) {
844                 plainErase();
845                 array().insert(pos(), a);
846                 if (goright) 
847                         pos() += a.size();
848         }
849 }
850
851
852 MathStyles MathCursor::style() const
853 {
854         return xarray().style();
855 }
856
857
858 void MathCursor::normalize() const
859 {
860 #ifdef WITH_WARNINGS
861 #warning This is evil!
862 #endif
863         MathCursor * it = const_cast<MathCursor *>(this);
864
865         if (idx() < 0)
866                 lyxerr << "this should not really happen - 1: " << idx() << "\n";
867         if (idx() >= par()->nargs()) {
868                 lyxerr << "this should not really happen - 2: "
869                        << idx() << " " << par()->nargs() << "\n";
870                 dump("error 2");
871         }
872         it->idx()    = max(idx(), 0);
873         it->idx()    = min(idx(), par()->nargs() - 1);
874
875         if (pos() < 0)
876                 lyxerr << "this should not really happen - 3: " << pos() << "\n";
877         if (pos() > size()) {
878                 lyxerr << "this should not really happen - 4: "
879                        << pos() << " " << size() << "\n";
880                 dump("error 4");
881         }
882         it->pos() = max(pos(), 0);
883         it->pos() = min(pos(), size());
884 }
885
886
887 int MathCursor::size() const
888 {
889         return array().size();
890 }
891
892
893 int MathCursor::col() const
894 {
895         return par()->col(idx());
896 }
897
898
899 int MathCursor::row() const
900 {
901         return par()->row(idx());
902 }
903
904
905 /*
906 char MathCursorPos::getChar() const
907 {
908         return array().getChar(pos());
909 }
910
911
912 string MathCursorPos::readString()
913 {
914         string s;
915         int code = nextCode();
916         for ( ; OK() && nextCode() == code; Next()) 
917                 s += getChar();
918
919         return s;
920 }
921 */
922
923
924 MathInset * MathCursor::prevInset() const
925 {
926         return prevAtom() ? prevAtom()->nucleus() : 0;
927 }
928
929
930 MathInset * MathCursor::nextInset() const
931 {
932         return nextAtom() ? nextAtom()->nucleus() : 0;
933 }
934
935
936 MathSpaceInset * MathCursor::prevSpaceInset() const
937 {
938         MathInset * p = prevInset();
939         return (p && p->isSpaceInset()) ? static_cast<MathSpaceInset *>(p) : 0;
940 }
941
942
943 MathAtom const * MathCursor::prevAtom() const
944 {
945         return array().at(pos() - 1);
946 }
947
948
949 MathAtom * MathCursor::prevAtom()
950 {
951         return array().at(pos() - 1);
952 }
953
954
955 MathAtom const * MathCursor::nextAtom() const
956 {
957         return array().at(pos());
958 }
959
960
961 MathAtom * MathCursor::nextAtom()
962 {
963         return array().at(pos());
964 }
965
966
967 MathArray & MathCursor::array() const
968 {
969         static MathArray dummy;
970         if (!par()) {
971                 lyxerr << "############  par_ not valid\n";
972                 return dummy;
973         }
974
975         if (idx() < 0 || idx() >= par()->nargs()) {
976                 lyxerr << "############  idx_ " << idx() << " not valid\n";
977                 return dummy;
978         }
979
980         return cursor().cell();
981 }
982
983
984 MathXArray & MathCursor::xarray() const
985 {
986         return cursor().xcell();
987 }
988
989
990 void MathCursor::idxNext()
991 {
992         par()->idxNext(idx(), pos());
993 }
994
995
996 void MathCursor::idxPrev()
997 {
998         par()->idxPrev(idx(), pos());
999 }
1000
1001
1002 void MathCursor::splitCell()
1003 {
1004         if (idx() == par()->nargs() - 1) 
1005                 return;
1006         MathArray ar = array();
1007         ar.erase(0, pos());
1008         array().erase(pos(), size());
1009         ++idx();
1010         pos() = 0;
1011         array().insert(0, ar);
1012 }
1013
1014
1015 void MathCursor::breakLine()
1016 {
1017         // leave inner cells
1018         while (popRight())
1019                 ;
1020
1021         MathMatrixInset * p = outerPar();
1022         if (p->getType() == LM_OT_SIMPLE || p->getType() == LM_OT_EQUATION) {
1023                 p->mutate(LM_OT_EQNARRAY);
1024                 idx() = 0;
1025                 pos() = size();
1026         } else {
1027                 p->addRow(row());
1028
1029                 // split line
1030                 const int r = row();
1031                 for (int c = col() + 1; c < p->ncols(); ++c) {
1032                         const int i1 = p->index(r, c);
1033                         const int i2 = p->index(r + 1, c);      
1034                         lyxerr << "swapping cells " << i1 << " and " << i2 << "\n";
1035                         p->cell(i1).swap(p->cell(i2));
1036                 }
1037
1038                 // split cell
1039                 splitCell();
1040                 p->cell(idx()).swap(p->cell(idx() + p->ncols() - 1));
1041         }
1042 }
1043
1044
1045 char MathCursor::valign() const
1046 {
1047         int idx;
1048         MathArrayInset * p = enclosingArray(idx);
1049         return p ? p->valign() : 0;
1050 }
1051
1052
1053 char MathCursor::halign() const
1054 {
1055         int idx;
1056         MathArrayInset * p = enclosingArray(idx);
1057         return p ? p->halign(idx % p->ncols()) : 0;
1058 }
1059
1060
1061 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1062 {
1063         MathCursorPos anc = normalAnchor();
1064         if (anc < cursor()) {
1065                 i1 = anc;
1066                 i2 = cursor();
1067         } else {
1068                 i1 = cursor();
1069                 i2 = anc;
1070         }
1071 }
1072
1073
1074 MathCursorPos & MathCursor::cursor()
1075 {
1076         return Cursor_.back();
1077 }
1078
1079
1080 MathCursorPos const & MathCursor::cursor() const
1081 {
1082         return Cursor_.back();
1083 }
1084
1085
1086 int MathCursor::cellXOffset() const
1087 {
1088         return par()->cellXOffset(idx());
1089 }
1090
1091
1092 int MathCursor::cellYOffset() const
1093 {
1094         return par()->cellYOffset(idx());
1095 }
1096
1097
1098 int MathCursor::xpos() const
1099 {
1100         return cellXOffset() + xarray().pos2x(pos());
1101 }
1102
1103
1104 int MathCursor::ypos() const
1105 {
1106         return cellYOffset();
1107 }
1108
1109
1110
1111 void MathCursor::gotoX(int x) 
1112 {
1113         pos() = xarray().x2pos(x - cellXOffset());
1114 }
1115
1116
1117 bool MathCursor::goUp()
1118 {
1119         // first ask the inset if it knows better then we
1120         if (par()->idxUp(idx(), pos()))
1121                 return true;
1122
1123         // if not, apply brute force.
1124         int x0;
1125         int y0;
1126         getPos(x0, y0);
1127         std::vector<MathCursorPos> save = Cursor_;
1128         y0 -= xarray().ascent();
1129         for (int y = y0 - 4; y > outerPar()->yo() - outerPar()->ascent(); y -= 4) {
1130                 setPos(x0, y);
1131                 if (save != Cursor_ && xarray().yo() < y0)
1132                         return true;    
1133         }
1134         Cursor_ = save;
1135         return false;
1136 }
1137
1138
1139 bool MathCursor::goDown()
1140 {
1141         // first ask the inset if it knows better then we
1142         if (par()->idxDown(idx(), pos()))
1143                 return true;
1144
1145         // if not, apply brute force.
1146         int x0;
1147         int y0;
1148         getPos(x0, y0);
1149         std::vector<MathCursorPos> save = Cursor_;
1150         y0 += xarray().descent();
1151         for (int y = y0 + 4; y < outerPar()->yo() + outerPar()->descent(); y += 4) {
1152                 setPos(x0, y);
1153                 if (save != Cursor_ && xarray().yo() > y0)
1154                         return true;    
1155         }
1156         Cursor_ = save;
1157         return false;
1158 }
1159
1160
1161 bool MathCursor::idxLeft()
1162 {
1163         return par()->idxLeft(idx(), pos());
1164 }
1165
1166
1167 bool MathCursor::idxRight()
1168 {
1169         return par()->idxRight(idx(), pos());
1170 }
1171
1172
1173 MathMatrixInset * MathCursor::outerPar() const
1174 {
1175         return
1176                 static_cast<MathMatrixInset *>(const_cast<MathInset *>(formula_->par()));
1177 }
1178
1179
1180 void MathCursor::interpret(string const & s)
1181 {
1182         //lyxerr << "interpret: '" << s << "'\n";
1183         //lyxerr << "in: " << in_word_set(s) << " \n";
1184
1185         if (s.empty())
1186                 return;
1187
1188         char c = s[0];
1189
1190         //lyxerr << "char: '" << c << "'  int: " << int(c) << endl;
1191         //owner_->getIntl()->getTrans().TranslateAndInsert(c, lt);      
1192         //lyxerr << "trans: '" << c << "'  int: " << int(c) << endl;
1193
1194         if (s.size() > 7 && s.substr(0, 7) == "matrix ") {
1195                 int m = 1;
1196                 int n = 1;
1197                 string v_align;
1198                 string h_align;
1199                 istringstream is(s.substr(7).c_str());
1200                 is >> m >> n >> v_align >> h_align;
1201                 m = std::max(1, m);
1202                 n = std::max(1, n);
1203                 v_align += 'c';
1204                 MathArrayInset * p = new MathArrayInset(m, n);
1205                 p->valign(v_align[0]);
1206                 p->halign(h_align);
1207                 niceInsert(p);
1208                 return;
1209         }
1210
1211         if (s == "\\over" || s == "\\choose" || s == "\\atop") {
1212                 MathArray ar = array();
1213                 MathInset * p = createMathInset(s.substr(1));
1214                 p->cell(0).swap(array());
1215                 pos() = 0;
1216                 niceInsert(p);
1217                 popRight();
1218                 left();
1219                 return;
1220         }
1221
1222         if (s.size() > 1) {
1223                 niceInsert(createMathInset(s.substr(1)));
1224                 return;
1225         }
1226
1227
1228         // we got just a single char now
1229
1230         if (c == '^' || c == '_') {
1231                 bool const up = (s[0] == '^');
1232                 selCut();       
1233                 if (!prevInset()) {
1234                         insert('{', LM_TC_TEX);
1235                         insert('}', LM_TC_TEX);
1236                 }
1237                 MathInset * par = prevAtom()->ensure(up);
1238                 pushRight(par);
1239                 selPaste();
1240                 return;
1241         }
1242
1243         if (selection_)
1244                 selDel();
1245
1246         if (lastcode_ == LM_TC_TEXTRM) {
1247                 insert(c, LM_TC_TEXTRM);
1248                 return;
1249         }
1250
1251         if (c == ' ') {
1252                 if (inMacroMode()) {
1253                         macroModeClose();
1254                         lastcode_ = LM_TC_VAR;
1255                         return;
1256                 }
1257
1258                 MathSpaceInset * p = prevSpaceInset();
1259                 if (p) {
1260                         p->incSpace();
1261                         return;
1262                 }
1263
1264                 if (mathcursor->popRight())
1265                         return;
1266
1267 #warning look here
1268                         // this would not work if the inset is in an table!
1269                         //bv->text->cursorRight(bv, true);
1270                         //result = FINISHED;
1271                 return;
1272         }
1273
1274         if (lastcode_ != LM_TC_TEX && strchr("#$%{}", c)) {
1275                 insert(new MathSpecialCharInset(c));    
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