]> git.lyx.org Git - features.git/blob - src/mathed/math_cursor.C
*** empty log message ***
[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                 return;
641         }
642
643         plainErase();
644 }
645
646
647 void MathCursor::delLine()
648 {
649         macroModeClose();
650
651         if (selection_) {
652                 selDel();
653                 return;
654         }
655
656         if (par()->nrows() > 1)
657                 par()->delRow(row());
658 }
659
660
661 bool MathCursor::up(bool sel)
662 {
663         dump("up 1");
664         macroModeClose();
665         selHandle(sel);
666
667         if (selection_)
668                 return goUp();
669
670         // check whether we could move into a superscript on the right or on the left
671         if (prevAtom() && prevAtom()->up()) {
672                 pushRight(prevAtom()->up());            
673                 return true;
674         }
675
676         if (nextAtom() && nextAtom()->up()) {
677                 pushLeft(nextAtom()->up());             
678                 return true;
679         }
680
681         return goUp();
682 }
683
684
685 bool MathCursor::down(bool sel)
686 {
687         dump("down 1");
688         macroModeClose();
689         selHandle(sel);
690
691         if (selection_) 
692                 return goDown();
693
694         // check whether we could move into an subscript on the right or on the left
695         if (prevAtom() && prevAtom()->down()) {
696                 pushRight(prevAtom()->down());          
697                 return true;
698         }
699
700         if (nextAtom() && nextAtom()->down()) {
701                 pushLeft(nextAtom()->down());   
702                 return true;
703         }
704
705         return goDown();
706 }
707
708
709 bool MathCursor::toggleLimits()
710 {
711         MathAtom * t = prevAtom();
712         if (!t)
713                 return false;
714         int old = t->limits();
715         t->limits(old < 0 ? 1 : -1);
716         return old != t->limits();
717 }
718
719
720 void MathCursor::setSize(MathStyles size)
721 {
722         par()->userSetSize(size);
723 }
724
725
726 void MathCursor::macroModeClose()
727 {
728         string s = macroName();
729         if (s.size()) {
730                 pos() = pos() - s.size() - 1;
731                 for (unsigned i = 0; i <= s.size(); ++i)
732                         plainErase();
733                 lastcode_ = LM_TC_VAR;
734                 interpret("\\" + s);
735         }
736 }
737
738
739 string MathCursor::macroName() const
740 {
741         string s;
742         for (int i = pos() - 1; i >= 0; --i) {
743                 MathInset * p = array().at(i)->nucleus();
744                 if (!p || p->code() != LM_TC_TEX || p->getChar() == '\\')
745                         break;
746                 s = p->getChar() + s;
747         }
748         return s;
749 }
750
751
752 void MathCursor::selCopy()
753 {
754         seldump("selCopy");
755         if (selection_) {
756                 theSelection.grab(*this);
757                 selClear();
758         }
759 }
760
761
762 void MathCursor::selCut()
763 {
764         seldump("selCut");
765         if (selection_) {
766                 theSelection.grab(*this);
767                 theSelection.erase(*this);
768                 selClear();
769         } else {
770                 theSelection.clear();
771         }
772 }
773
774
775 void MathCursor::selDel()
776 {
777         seldump("selDel");
778         if (selection_) {
779                 theSelection.erase(*this);
780                 selClear();
781         }
782 }
783
784
785 void MathCursor::selPaste()
786 {
787         seldump("selPaste");
788         theSelection.paste(*this);
789         selClear();
790 }
791
792
793 void MathCursor::selHandle(bool sel)
794 {
795         if (sel == selection_)
796                 return;
797
798         theSelection.clear();
799         Anchor_    = Cursor_;
800         selection_ = sel;
801 }
802
803
804 void MathCursor::selStart()
805 {
806         seldump("selStart");
807         if (selection_)
808                 return;
809
810         theSelection.clear();
811         Anchor_ = Cursor_;
812         selection_ = true;
813 }
814
815
816 void MathCursor::selClear()
817 {
818         seldump("selClear");
819         selection_ = false;
820 }
821
822
823 void MathCursor::drawSelection(Painter & pain) const
824 {
825         if (!selection_)
826                 return;
827
828         MathCursorPos i1;
829         MathCursorPos i2;
830         getSelection(i1, i2);
831
832         //lyxerr << "selection from: " << i1 << " to " << i2 << "\n";
833
834         if (i1.idx_ == i2.idx_) {
835                 MathXArray & c = i1.xcell();
836                 int x1 = c.xo() + c.pos2x(i1.pos_, i1.inner_);
837                 int y1 = c.yo() - c.ascent();
838                 int x2 = c.xo() + c.pos2x(i2.pos_, i2.inner_);
839                 int y2 = c.yo() + c.descent();
840                 pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
841         } else {
842                 std::vector<MathInset::idx_type> indices = i1.par_->idxBetween(i1.idx_, i2.idx_);
843                 for (unsigned i = 0; i < indices.size(); ++i) {
844                         MathXArray & c = i1.xcell(indices[i]);
845                         int x1 = c.xo();
846                         int y1 = c.yo() - c.ascent();
847                         int x2 = c.xo() + c.width();
848                         int y2 = c.yo() + c.descent();
849                         pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
850                 }
851         }
852 }
853
854
855 MathTextCodes MathCursor::nextCode() const
856 {
857         //return (pos() == size()) ? LM_TC_VAR : nextInset()->code();
858         return LM_TC_VAR;
859 }
860
861
862 void MathCursor::handleFont(MathTextCodes t)
863 {
864         macroModeClose();
865         if (selection_) {
866                 MathCursorPos i1;
867                 MathCursorPos i2;
868                 getSelection(i1, i2); 
869                 if (i1.idx_ == i2.idx_) {
870                         MathArray & ar = i1.cell();
871                         for (MathInset::pos_type pos = i1.pos_;
872                              pos != i2.pos_; ++pos) {
873                                 MathInset * p = ar.at(pos)->nucleus();
874                                 if (p)
875                                         p->handleFont(t);
876                         }
877                 }
878         } else 
879                 lastcode_ = (lastcode_ == t) ? LM_TC_VAR : t;
880 }
881
882
883 void MathCursor::handleDelim(string const & l, string const & r)
884 {
885         handleNest(new MathDelimInset(l, r));
886 }
887
888
889 void MathCursor::handleNest(MathInset * p)
890 {
891         if (selection_) {
892                 selCut();
893                 p->cell(0) = theSelection.glue();
894         }
895         insert(p); // this invalidates p!
896         p = prevAtom()->nucleus();      
897         pushRight(p);
898 }
899
900
901 void MathCursor::getPos(int & x, int & y)
902 {
903 #ifdef WITH_WARNINGS
904 #warning This should probably take cellXOffset and cellYOffset into account
905 #endif
906         x = xarray().xo() + xarray().pos2x(pos(), inner());
907         y = xarray().yo();
908 }
909
910
911 MathInset * MathCursor::par() const
912 {
913         return cursor().par_;
914 }
915
916
917 InsetFormulaBase const * MathCursor::formula()
918 {
919         return formula_;
920 }
921
922
923 MathCursor::idx_type MathCursor::idx() const
924 {
925         return cursor().idx_;
926 }
927
928
929 MathCursor::idx_type & MathCursor::idx()
930 {
931         return cursor().idx_;
932 }
933
934
935 MathCursor::pos_type MathCursor::pos() const
936 {
937         return cursor().pos_;
938 }
939
940
941 MathCursor::pos_type & MathCursor::pos()
942 {
943         return cursor().pos_;
944 }
945
946
947 bool MathCursor::inner() const
948 {
949         return cursor().inner_;
950 }
951
952
953 bool & MathCursor::inner()
954 {
955         return cursor().inner_;
956 }
957
958
959 bool MathCursor::inMacroMode() const
960 {
961         return lastcode_ == LM_TC_TEX;
962 }
963
964
965 bool MathCursor::selection() const
966 {
967         return selection_;
968 }
969
970
971 MathArrayInset * MathCursor::enclosingArray(MathCursor::idx_type & idx) const
972 {
973         for (int i = Cursor_.size() - 1; i >= 0; --i) {
974                 if (Cursor_[i].par_->isArray()) {
975                         idx = Cursor_[i].idx_;
976                         return static_cast<MathArrayInset *>(Cursor_[i].par_);
977                 }
978         }
979         return 0;
980 }
981
982
983 void MathCursor::pullArg(bool goright)
984 {
985         // pullArg
986         dump("pullarg");
987         MathArray a = array();
988         if (popLeft()) {
989                 plainErase();
990                 array().insert(pos(), a);
991                 if (goright) 
992                         pos() += a.size();
993         }
994 }
995
996
997 MathStyles MathCursor::style() const
998 {
999         return xarray().style();
1000 }
1001
1002
1003 void MathCursor::normalize() const
1004 {
1005 #ifdef WITH_WARNINGS
1006 #warning This is evil!
1007 #endif
1008         MathCursor * it = const_cast<MathCursor *>(this);
1009
1010         if (idx() >= par()->nargs()) {
1011                 lyxerr << "this should not really happen - 1: "
1012                        << idx() << " " << par()->nargs() << "\n";
1013                 dump("error 2");
1014         }
1015         it->idx()    = min(idx(), par()->nargs() - 1);
1016
1017         if (pos() > size()) {
1018                 lyxerr << "this should not really happen - 2: "
1019                        << pos() << " " << size() << "\n";
1020                 dump("error 4");
1021         }
1022         it->pos() = min(pos(), size());
1023 }
1024
1025
1026 MathCursor::size_type MathCursor::size() const
1027 {
1028         return array().size();
1029 }
1030
1031
1032 MathCursor::col_type MathCursor::col() const
1033 {
1034         return par()->col(idx());
1035 }
1036
1037
1038 MathCursor::row_type MathCursor::row() const
1039 {
1040         return par()->row(idx());
1041 }
1042
1043
1044 /*
1045 char MathCursorPos::getChar() const
1046 {
1047         return array().getChar(pos());
1048 }
1049
1050
1051 string MathCursorPos::readString()
1052 {
1053         string s;
1054         int code = nextCode();
1055         for ( ; OK() && nextCode() == code; Next()) 
1056                 s += getChar();
1057
1058         return s;
1059 }
1060 */
1061
1062
1063 MathInset * MathCursor::prevInset() const
1064 {
1065         return prevAtom() ? prevAtom()->nucleus() : 0;
1066 }
1067
1068
1069 MathInset * MathCursor::nextInset() const
1070 {
1071         return nextAtom() ? nextAtom()->nucleus() : 0;
1072 }
1073
1074
1075 MathSpaceInset * MathCursor::prevSpaceInset() const
1076 {
1077         MathInset * p = prevInset();
1078         return (p && p->isSpaceInset()) ? static_cast<MathSpaceInset *>(p) : 0;
1079 }
1080
1081
1082 MathAtom const * MathCursor::prevAtom() const
1083 {
1084         return array().at(pos() - 1);
1085 }
1086
1087
1088 MathAtom * MathCursor::prevAtom()
1089 {
1090         return array().at(pos() - 1);
1091 }
1092
1093
1094 MathAtom const * MathCursor::nextAtom() const
1095 {
1096         return array().at(pos());
1097 }
1098
1099
1100 MathAtom * MathCursor::nextAtom()
1101 {
1102         return array().at(pos());
1103 }
1104
1105
1106 MathArray & MathCursor::array() const
1107 {
1108         static MathArray dummy;
1109         if (!par()) {
1110                 lyxerr << "############  par_ not valid\n";
1111                 return dummy;
1112         }
1113
1114         if (idx() >= par()->nargs()) {
1115                 lyxerr << "############  idx_ " << idx() << " not valid\n";
1116                 return dummy;
1117         }
1118
1119         return cursor().cell();
1120 }
1121
1122
1123 MathXArray & MathCursor::xarray() const
1124 {
1125         return cursor().xcell();
1126 }
1127
1128
1129 void MathCursor::idxNext()
1130 {
1131         par()->idxNext(idx(), pos());
1132 }
1133
1134
1135 void MathCursor::idxPrev()
1136 {
1137         par()->idxPrev(idx(), pos());
1138 }
1139
1140
1141 void MathCursor::splitCell()
1142 {
1143         if (idx() == par()->nargs() - 1) 
1144                 return;
1145         MathArray ar = array();
1146         ar.erase(0, pos());
1147         array().erase(pos(), size());
1148         ++idx();
1149         pos() = 0;
1150         array().insert(0, ar);
1151 }
1152
1153
1154 void MathCursor::breakLine()
1155 {
1156         // leave inner cells
1157         while (popRight())
1158                 ;
1159
1160         MathMatrixInset * p = outerPar();
1161         if (p->getType() == LM_OT_SIMPLE || p->getType() == LM_OT_EQUATION) {
1162                 p->mutate(LM_OT_EQNARRAY);
1163                 idx() = 0;
1164                 pos() = size();
1165         } else {
1166                 p->addRow(row());
1167
1168                 // split line
1169                 const row_type r = row();
1170                 for (col_type c = col() + 1; c < p->ncols(); ++c) {
1171                         const MathMatrixInset::idx_type i1 = p->index(r, c);
1172                         const MathMatrixInset::idx_type i2 = p->index(r + 1, c);        
1173                         lyxerr << "swapping cells " << i1 << " and " << i2 << "\n";
1174                         p->cell(i1).swap(p->cell(i2));
1175                 }
1176
1177                 // split cell
1178                 splitCell();
1179                 p->cell(idx()).swap(p->cell(idx() + p->ncols() - 1));
1180         }
1181 }
1182
1183
1184 char MathCursor::valign() const
1185 {
1186         idx_type idx;
1187         MathArrayInset * p = enclosingArray(idx);
1188         return p ? p->valign() : '\0';
1189 }
1190
1191
1192 char MathCursor::halign() const
1193 {
1194         idx_type idx;
1195         MathArrayInset * p = enclosingArray(idx);
1196         return p ? p->halign(idx % p->ncols()) : '\0';
1197 }
1198
1199
1200 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1201 {
1202         MathCursorPos anc = normalAnchor();
1203         if (anc < cursor()) {
1204                 i1 = anc;
1205                 i2 = cursor();
1206         } else {
1207                 i1 = cursor();
1208                 i2 = anc;
1209         }
1210 }
1211
1212
1213 MathCursorPos & MathCursor::cursor()
1214 {
1215         return Cursor_.back();
1216 }
1217
1218
1219 MathCursorPos const & MathCursor::cursor() const
1220 {
1221         return Cursor_.back();
1222 }
1223
1224
1225 int MathCursor::cellXOffset() const
1226 {
1227         return par()->cellXOffset(idx());
1228 }
1229
1230
1231 int MathCursor::cellYOffset() const
1232 {
1233         return par()->cellYOffset(idx());
1234 }
1235
1236
1237 int MathCursor::xpos() const
1238 {
1239         return cellXOffset() + xarray().pos2x(pos(), inner());
1240 }
1241
1242
1243 int MathCursor::ypos() const
1244 {
1245         return cellYOffset();
1246 }
1247
1248
1249
1250 void MathCursor::gotoX(int x) 
1251 {
1252         pos() = xarray().x2pos(x - cellXOffset());
1253 }
1254
1255
1256 bool MathCursor::goUp()
1257 {
1258         // first ask the inset if it knows better then we
1259         if (par()->idxUp(idx(), pos()))
1260                 return true;
1261
1262         // leave subscript to the nearest side  
1263         if (par()->asScriptInset() && par()->asScriptInset()->down()) {
1264                 if (pos() <= size() / 2)
1265                         popLeft();
1266                 else
1267                         popRight();             
1268                 return true;
1269         }
1270
1271         // if not, apply brute force.
1272         int x0;
1273         int y0;
1274         getPos(x0, y0);
1275         std::vector<MathCursorPos> save = Cursor_;
1276         y0 -= xarray().ascent();
1277         for (int y = y0 - 4; y > outerPar()->yo() - outerPar()->ascent(); y -= 4) {
1278                 setPos(x0, y);
1279                 if (save != Cursor_ && xarray().yo() < y0)
1280                         return true;    
1281         }
1282         Cursor_ = save;
1283         return false;
1284 }
1285
1286
1287 bool MathCursor::goDown()
1288 {
1289         // first ask the inset if it knows better then we
1290         if (par()->idxDown(idx(), pos()))
1291                 return true;
1292
1293         // leave superscript to the nearest side        
1294         if (par()->asScriptInset() && par()->asScriptInset()->up()) {
1295                 if (pos() <= size() / 2)
1296                         popLeft();
1297                 else
1298                         popRight();             
1299                 return true;
1300         }
1301
1302         // if not, apply brute force.
1303         int x0;
1304         int y0;
1305         getPos(x0, y0);
1306         std::vector<MathCursorPos> save = Cursor_;
1307         y0 += xarray().descent();
1308         for (int y = y0 + 4; y < outerPar()->yo() + outerPar()->descent(); y += 4) {
1309                 setPos(x0, y);
1310                 if (save != Cursor_ && xarray().yo() > y0)
1311                         return true;    
1312         }
1313         Cursor_ = save;
1314         return false;
1315 }
1316
1317
1318 bool MathCursor::idxLeft()
1319 {
1320         return par()->idxLeft(idx(), pos());
1321 }
1322
1323
1324 bool MathCursor::idxRight()
1325 {
1326         return par()->idxRight(idx(), pos());
1327 }
1328
1329
1330 MathMatrixInset * MathCursor::outerPar() const
1331 {
1332         return
1333                 static_cast<MathMatrixInset *>(const_cast<MathInset *>(formula_->par()));
1334 }
1335
1336
1337 void MathCursor::interpret(string const & s)
1338 {
1339         //lyxerr << "interpret: '" << s << "'\n";
1340         //lyxerr << "in: " << in_word_set(s) << " \n";
1341
1342         if (s.empty())
1343                 return;
1344
1345         char c = s[0];
1346
1347         //lyxerr << "char: '" << c << "'  int: " << int(c) << endl;
1348         //owner_->getIntl()->getTrans().TranslateAndInsert(c, lt);      
1349         //lyxerr << "trans: '" << c << "'  int: " << int(c) << endl;
1350
1351         if (s.size() > 7 && s.substr(0, 7) == "matrix ") {
1352                 unsigned int m = 1;
1353                 unsigned int n = 1;
1354                 string v_align;
1355                 string h_align;
1356                 istringstream is(s.substr(7).c_str());
1357                 is >> m >> n >> v_align >> h_align;
1358                 m = std::max(1u, m);
1359                 n = std::max(1u, n);
1360                 v_align += 'c';
1361                 MathArrayInset * p = new MathArrayInset(m, n);
1362                 p->valign(v_align[0]);
1363                 p->halign(h_align);
1364                 niceInsert(p);
1365                 return;
1366         }
1367
1368         if (s == "\\over" || s == "\\choose" || s == "\\atop") {
1369                 MathArray ar = array();
1370                 MathInset * p = createMathInset(s.substr(1));
1371                 p->cell(0).swap(array());
1372                 pos() = 0;
1373                 niceInsert(p);
1374                 popRight();
1375                 left();
1376                 return;
1377         }
1378
1379         if (s.size() > 1) {
1380                 niceInsert(createMathInset(s.substr(1)));
1381                 return;
1382         }
1383
1384
1385         // we got just a single char now
1386
1387         if (c == '^' || c == '_') {
1388                 const bool up = (s[0] == '^');
1389                 selCut();
1390                 if (inner())
1391                         ++pos();
1392                 if (!prevAtom())
1393                         insert(0);
1394                 MathInset * par = prevAtom()->ensure(up);
1395                 pushRight(par);
1396                 selPaste();
1397                 return;
1398         }
1399
1400         if (selection_)
1401                 selDel();
1402
1403         if (lastcode_ == LM_TC_TEXTRM) {
1404                 insert(c, LM_TC_TEXTRM);
1405                 return;
1406         }
1407
1408         if (c == ' ') {
1409                 if (inMacroMode()) {
1410                         macroModeClose();
1411                         lastcode_ = LM_TC_VAR;
1412                         return;
1413                 }
1414
1415                 MathSpaceInset * p = prevSpaceInset();
1416                 if (p) {
1417                         p->incSpace();
1418                         return;
1419                 }
1420
1421                 if (mathcursor->popRight())
1422                         return;
1423
1424 #warning look here
1425                         // this would not work if the inset is in an table!
1426                         //bv->text->cursorRight(bv, true);
1427                         //result = FINISHED;
1428                 return;
1429         }
1430
1431         if (lastcode_ != LM_TC_TEX && strchr("{}", c)) {
1432                 insert(c, LM_TC_TEX);
1433                 return;
1434         }
1435
1436         if (lastcode_ != LM_TC_TEX && strchr("#$%", c)) {
1437                 insert(new MathSpecialCharInset(c));    
1438                 lastcode_ = LM_TC_VAR;
1439                 return;
1440         }
1441
1442         if (lastcode_ == LM_TC_TEX) {
1443                 if (macroName().empty()) {
1444                         insert(c, LM_TC_TEX);
1445                         if (!isalpha(c) && c != '#') {
1446                                 macroModeClose();
1447                                 lastcode_ = LM_TC_VAR;
1448                         }
1449                 } else {
1450                         if ('1' <= c && c <= '9' && macroName() == "#") {
1451                                 insert(c, LM_TC_TEX);
1452                                 macroModeClose();
1453                                 lastcode_ = LM_TC_VAR;
1454                         }
1455                         else if (isalpha(c)) {
1456                                 insert(c, LM_TC_TEX);
1457                         }
1458                         else {
1459                                 macroModeClose();
1460                                 lastcode_ = LM_TC_VAR;
1461                         }
1462                 }
1463                 return;
1464         }
1465
1466         if (isalpha(c) && (lastcode_ == LM_TC_GREEK || lastcode_ == LM_TC_GREEK1)) {
1467                 static char const greekl[][26] =
1468                         {"alpha", "beta", "chi", "delta", "epsilon", "phi",
1469                          "gamma", "eta", "iota", "iota", "kappa", "lambda", "mu",
1470                          "nu", "omikron", "pi", "omega", "rho", "sigma",
1471                          "tau", "upsilon", "theta", "omega", "xi", "upsilon", "zeta"};
1472                 static char const greeku[][26] =
1473                         {"Alpha", "Beta", "Chi", "Delta", "Epsilon", "Phi",
1474                          "Gamma", "Eta", "Iota", "Iota", "Kappa", "Lambda", "Mu",
1475                          "Nu", "Omikron", "Pi", "Omega", "Rho", "Sigma", "Tau",
1476                          "Upsilon", "Theta", "Omega", "xi", "Upsilon", "Zeta"};
1477         
1478                 latexkeys const * l = 0;        
1479                 if ('a' <= c && c <= 'z')
1480                         l = in_word_set(greekl[c - 'a']);
1481                 if ('A' <= c && c <= 'Z')
1482                         l = in_word_set(greeku[c - 'A']);
1483         
1484                 if (l)
1485                         insert(createMathInset(l));
1486                 else
1487                         insert(c, LM_TC_VAR);
1488
1489 #warning greek insert problem? look here!
1490                 if (lastcode_ == LM_TC_GREEK1)
1491                         lastcode_ = LM_TC_VAR;
1492                 return; 
1493         }
1494
1495         if (c == '\\') {
1496                 lastcode_ = LM_TC_TEX;
1497                 insert(c, LM_TC_TEX);
1498                 //bv->owner()->message(_("TeX mode"));
1499                 return; 
1500         }
1501
1502         // no special circumstances, so insert the character without any fuss
1503         insert(c, LM_TC_MIN);
1504 }
1505
1506
1507
1508 ////////////////////////////////////////////////////////////////////////
1509
1510
1511 bool operator==(MathCursorPos const & ti, MathCursorPos const & it)
1512 {
1513         return ti.par_ == it.par_ && ti.idx_ == it.idx_ && ti.pos_ == it.pos_;
1514 }
1515
1516
1517 bool operator<(MathCursorPos const & ti, MathCursorPos const & it)
1518 {
1519         if (ti.par_ != it.par_) {
1520                 lyxerr << "can't compare cursor and anchor in different insets\n";
1521                 return true;
1522         }
1523         if (ti.idx_ != it.idx_)
1524                 return ti.idx_ < it.idx_;
1525         return ti.pos_ < it.pos_;
1526 }
1527
1528
1529 MathArray & MathCursorPos::cell(MathCursor::idx_type idx) const
1530 {
1531         return par_->cell(idx);
1532 }
1533
1534
1535 MathArray & MathCursorPos::cell() const
1536 {
1537         return par_->cell(idx_);
1538 }
1539
1540
1541 MathXArray & MathCursorPos::xcell(MathCursor::idx_type idx) const
1542 {
1543         return par_->xcell(idx);
1544 }
1545
1546
1547 MathXArray & MathCursorPos::xcell() const
1548 {
1549         return par_->xcell(idx_);
1550 }
1551
1552
1553 MathAtom * MathCursorPos::at() const
1554 {
1555         return cell().at(pos_);
1556 }
1557
1558
1559 MathCursorPos MathCursor::normalAnchor() const
1560 {
1561         // use Anchor on the same level as Cursor
1562         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1563         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1564                 // anchor is behind cursor -> move anchor behind the inset
1565                 ++normal.pos_;
1566         }
1567         return normal;
1568 }
1569