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