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