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