]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
5db7ff3c264dab1bd9328f5f2368729356a50fce
[lyx.git] / src / mathed / math_cursor.C
1 /*
2  *  File:        math_cursor.C
3  *  Purpose:     Interaction for mathed
4  *  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx>
5  *  Created:     January 1996
6  *  Description: Math interaction for a WYSIWYG math editor.
7  *
8  *  Dependencies: Xlib, XForms
9  *
10  *  Copyright: 1996, Alejandro Aguilar Sierra
11  *
12  *   Version: 0.8beta, Math & Lyx project.
13  *
14  *   You are free to use and modify this code under the terms of
15  *   the GNU General Public Licence version 2 or later.
16  */
17
18 #ifdef __GNUG__
19 #pragma implementation
20 #endif
21
22 #include <config.h>
23 #include <algorithm>
24 #include <cctype>
25
26 #include "support/lstrings.h"
27 #include "debug.h"
28 #include "LColor.h"
29 #include "Painter.h"
30 #include "support.h"
31 #include "formulabase.h"
32 #include "math_cursor.h"
33 #include "math_factory.h"
34 #include "math_arrayinset.h"
35 #include "math_charinset.h"
36 #include "math_deliminset.h"
37 #include "math_matrixinset.h"
38 #include "math_scriptinset.h"
39 #include "math_spaceinset.h"
40 #include "math_specialcharinset.h"
41 #include "math_parser.h"
42
43 #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                 if (prevAtom() && nextAtom()) // should be unnecessary
476                         swap(prevAtom()->nucleus(), nextAtom()->nucleus());
477                 return;
478         }
479
480         MathAtom * n = nextAtom();
481
482         if (n && !n->nucleus()) {
483                 n->nucleus() = p;
484                 inner() = true;
485                 return;
486         }
487
488         array().insert(pos(), p); // this invalidates the pointer!
489         ++pos();
490 }
491
492
493 void MathCursor::insert(char c, MathTextCodes t)
494 {
495         //lyxerr << "inserting '" << c << "'\n";
496         plainInsert(new MathCharInset(c, t));
497 }
498
499
500 void MathCursor::insert(MathInset * p)
501 {
502         macroModeClose();
503
504         if (p && selection_) {
505                 if (p->nargs())
506                         selCut();
507                 else
508                         selDel();
509         }
510
511         plainInsert(p);
512 }
513
514
515 void MathCursor::niceInsert(MathInset * p) 
516 {
517         if (!p) {
518                 lyxerr << "MathCursor::niceInsert: should not happen\n";
519                 return;
520         }
521         selCut();
522         //cerr << "\n2: "; p->write(cerr, true); cerr << "\n";
523         insert(p); // inserting invalidates the pointer!
524         p = prevAtom()->nucleus();
525         //cerr << "\n3: "; p->write(cerr, true); cerr << "\n";
526         if (p->nargs()) {
527                 posLeft();
528                 right();  // do not push for e.g. MathSymbolInset
529                 selPaste();
530         }
531         p->metrics(p->size());
532 }
533
534
535 void MathCursor::insert(MathArray const & ar)
536 {
537         macroModeClose();
538         if (selection_)
539                 selCut();
540
541         array().insert(pos(), ar);
542         pos() += ar.size();
543 }
544
545
546 void MathCursor::glueAdjacentAtoms()
547 {
548         MathAtom * p = prevAtom();
549         if (!p)
550                 return;
551
552         MathAtom * n = nextAtom();
553         if (!n)
554                 return;
555
556         if (p->up() && n->up())
557                 return;
558
559         if (p->down() && n->down())
560                 return;
561
562         // move everything to the previous atom
563         if (n->up())
564                 swap(p->up(), n->up());
565
566         if (n->down())
567                 swap(p->down(), n->down());
568         
569         plainErase();
570         --pos();
571         inner() = nextAtom()->hasInner();
572 }
573
574
575 void MathCursor::backspace()
576 {
577         if (inner()) {
578                 nextAtom()->removeNucleus();
579                 inner() = false;
580                 glueAdjacentAtoms();
581                 return;
582         }
583
584         if (pos() == 0) {
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                 size_type old = pos();
732                 pos() -= s.size();
733                 array().erase(pos(), old);
734                 interpret(s);
735         }
736 }
737
738
739 int MathCursor::macroNamePos() const
740 {
741         for (int i = pos() - 1; i >= 0; --i) { 
742                 MathInset * p = array().at(i)->nucleus();
743                 if (p && p->code() == LM_TC_TEX && p->getChar() == '\\')
744                         return i;
745         }
746         return -1;
747 }
748
749
750 string MathCursor::macroName() const
751 {
752         string s;
753         for (int i = macroNamePos(); i >= 0 && i < int(pos()); ++i) 
754                 s += array().at(i)->nucleus()->getChar();
755         return s;
756 }
757
758
759 void MathCursor::selCopy()
760 {
761         seldump("selCopy");
762         if (selection_) {
763                 theSelection.grab(*this);
764                 selClear();
765         }
766 }
767
768
769 void MathCursor::selCut()
770 {
771         seldump("selCut");
772         if (selection_) {
773                 theSelection.grab(*this);
774                 theSelection.erase(*this);
775                 selClear();
776         } else {
777                 theSelection.clear();
778         }
779 }
780
781
782 void MathCursor::selDel()
783 {
784         seldump("selDel");
785         if (selection_) {
786                 theSelection.erase(*this);
787                 selClear();
788         }
789 }
790
791
792 void MathCursor::selPaste()
793 {
794         seldump("selPaste");
795         theSelection.paste(*this);
796         selClear();
797 }
798
799
800 void MathCursor::selHandle(bool sel)
801 {
802         if (sel == selection_)
803                 return;
804
805         theSelection.clear();
806         Anchor_    = Cursor_;
807         selection_ = sel;
808 }
809
810
811 void MathCursor::selStart()
812 {
813         seldump("selStart");
814         if (selection_)
815                 return;
816
817         theSelection.clear();
818         Anchor_ = Cursor_;
819         selection_ = true;
820 }
821
822
823 void MathCursor::selClear()
824 {
825         seldump("selClear");
826         selection_ = false;
827 }
828
829
830 void MathCursor::drawSelection(Painter & pain) const
831 {
832         if (!selection_)
833                 return;
834
835         MathCursorPos i1;
836         MathCursorPos i2;
837         getSelection(i1, i2);
838
839         //lyxerr << "selection from: " << i1 << " to " << i2 << "\n";
840
841         if (i1.idx_ == i2.idx_) {
842                 MathXArray & c = i1.xcell();
843                 int x1 = c.xo() + c.pos2x(i1.pos_, i1.inner_);
844                 int y1 = c.yo() - c.ascent();
845                 int x2 = c.xo() + c.pos2x(i2.pos_, i2.inner_);
846                 int y2 = c.yo() + c.descent();
847                 pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
848         } else {
849                 std::vector<MathInset::idx_type> indices = i1.par_->idxBetween(i1.idx_, i2.idx_);
850                 for (unsigned i = 0; i < indices.size(); ++i) {
851                         MathXArray & c = i1.xcell(indices[i]);
852                         int x1 = c.xo();
853                         int y1 = c.yo() - c.ascent();
854                         int x2 = c.xo() + c.width();
855                         int y2 = c.yo() + c.descent();
856                         pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
857                 }
858         }
859 }
860
861
862 MathTextCodes MathCursor::nextCode() const
863 {
864         //return (pos() == size()) ? LM_TC_VAR : nextInset()->code();
865         return LM_TC_VAR;
866 }
867
868
869 void MathCursor::handleFont(MathTextCodes t)
870 {
871         macroModeClose();
872         if (selection_) {
873                 MathCursorPos i1;
874                 MathCursorPos i2;
875                 getSelection(i1, i2); 
876                 if (i1.idx_ == i2.idx_) {
877                         MathArray & ar = i1.cell();
878                         for (MathInset::pos_type pos = i1.pos_;
879                              pos != i2.pos_; ++pos) {
880                                 MathInset * p = ar.at(pos)->nucleus();
881                                 if (p)
882                                         p->handleFont(t);
883                         }
884                 }
885         } else 
886                 lastcode_ = (lastcode_ == t) ? LM_TC_VAR : t;
887 }
888
889
890 void MathCursor::handleDelim(string const & l, string const & r)
891 {
892         handleNest(new MathDelimInset(l, r));
893 }
894
895
896 void MathCursor::handleNest(MathInset * p)
897 {
898         if (selection_) {
899                 selCut();
900                 p->cell(0) = theSelection.glue();
901         }
902         insert(p); // this invalidates p!
903         p = prevAtom()->nucleus();      
904         pushRight(p);
905 }
906
907
908 void MathCursor::getPos(int & x, int & y)
909 {
910 #ifdef WITH_WARNINGS
911 #warning This should probably take cellXOffset and cellYOffset into account
912 #endif
913         x = xarray().xo() + xarray().pos2x(pos(), inner());
914         y = xarray().yo();
915 }
916
917
918 MathInset * MathCursor::par() const
919 {
920         return cursor().par_;
921 }
922
923
924 InsetFormulaBase const * MathCursor::formula()
925 {
926         return formula_;
927 }
928
929
930 MathCursor::idx_type MathCursor::idx() const
931 {
932         return cursor().idx_;
933 }
934
935
936 MathCursor::idx_type & MathCursor::idx()
937 {
938         return cursor().idx_;
939 }
940
941
942 MathCursor::pos_type MathCursor::pos() const
943 {
944         return cursor().pos_;
945 }
946
947
948 MathCursor::pos_type & MathCursor::pos()
949 {
950         return cursor().pos_;
951 }
952
953
954 bool MathCursor::inner() const
955 {
956         return cursor().inner_;
957 }
958
959
960 bool & MathCursor::inner()
961 {
962         return cursor().inner_;
963 }
964
965
966 bool MathCursor::inMacroMode() const
967 {
968         return macroNamePos() != -1;
969 }
970
971
972 bool MathCursor::selection() const
973 {
974         return selection_;
975 }
976
977
978 MathArrayInset * MathCursor::enclosingArray(MathCursor::idx_type & idx) const
979 {
980         for (int i = Cursor_.size() - 1; i >= 0; --i) {
981                 if (Cursor_[i].par_->isArray()) {
982                         idx = Cursor_[i].idx_;
983                         return static_cast<MathArrayInset *>(Cursor_[i].par_);
984                 }
985         }
986         return 0;
987 }
988
989
990 void MathCursor::pullArg(bool goright)
991 {
992         dump("pullarg");
993         MathArray a = array();
994
995         MathScriptInset const * p = par()->asScriptInset();
996         if (p) {
997                 // special handling for scripts
998                 const bool up = p->up();
999                 popLeft();
1000                 if (nextAtom()) {
1001                         if (up)
1002                                 nextAtom()->removeUp();
1003                         else
1004                                 nextAtom()->removeDown();
1005                 }
1006                 ++pos();
1007                 array().insert(pos(), a);
1008                 return;
1009         }
1010
1011         if (popLeft()) {
1012                 plainErase();
1013                 array().insert(pos(), a);
1014                 if (goright) 
1015                         pos() += a.size();
1016         }
1017 }
1018
1019
1020 MathStyles MathCursor::style() const
1021 {
1022         return xarray().style();
1023 }
1024
1025
1026 void MathCursor::normalize() const
1027 {
1028 #ifdef WITH_WARNINGS
1029 #warning This is evil!
1030 #endif
1031         MathCursor * it = const_cast<MathCursor *>(this);
1032
1033         if (idx() >= par()->nargs()) {
1034                 lyxerr << "this should not really happen - 1: "
1035                        << idx() << " " << par()->nargs() << "\n";
1036                 dump("error 2");
1037         }
1038         it->idx()    = min(idx(), par()->nargs() - 1);
1039
1040         if (pos() > size()) {
1041                 lyxerr << "this should not really happen - 2: "
1042                        << pos() << " " << size() << "\n";
1043                 dump("error 4");
1044         }
1045         it->pos() = min(pos(), size());
1046 }
1047
1048
1049 MathCursor::size_type MathCursor::size() const
1050 {
1051         return array().size();
1052 }
1053
1054
1055 MathCursor::col_type MathCursor::col() const
1056 {
1057         return par()->col(idx());
1058 }
1059
1060
1061 MathCursor::row_type MathCursor::row() const
1062 {
1063         return par()->row(idx());
1064 }
1065
1066
1067 /*
1068 char MathCursorPos::getChar() const
1069 {
1070         return array().getChar(pos());
1071 }
1072
1073
1074 string MathCursorPos::readString()
1075 {
1076         string s;
1077         int code = nextCode();
1078         for ( ; OK() && nextCode() == code; Next()) 
1079                 s += getChar();
1080
1081         return s;
1082 }
1083 */
1084
1085
1086 MathInset * MathCursor::prevInset() const
1087 {
1088         return prevAtom() ? prevAtom()->nucleus() : 0;
1089 }
1090
1091
1092 MathInset * MathCursor::nextInset() const
1093 {
1094         return nextAtom() ? nextAtom()->nucleus() : 0;
1095 }
1096
1097
1098 MathSpaceInset * MathCursor::prevSpaceInset() const
1099 {
1100         MathInset * p = prevInset();
1101         return (p && p->isSpaceInset()) ? static_cast<MathSpaceInset *>(p) : 0;
1102 }
1103
1104
1105 MathAtom const * MathCursor::prevAtom() const
1106 {
1107         return array().at(pos() - 1);
1108 }
1109
1110
1111 MathAtom * MathCursor::prevAtom()
1112 {
1113         return array().at(pos() - 1);
1114 }
1115
1116
1117 MathAtom const * MathCursor::nextAtom() const
1118 {
1119         return array().at(pos());
1120 }
1121
1122
1123 MathAtom * MathCursor::nextAtom()
1124 {
1125         return array().at(pos());
1126 }
1127
1128
1129 MathArray & MathCursor::array() const
1130 {
1131         static MathArray dummy;
1132         if (!par()) {
1133                 lyxerr << "############  par_ not valid\n";
1134                 return dummy;
1135         }
1136
1137         if (idx() >= par()->nargs()) {
1138                 lyxerr << "############  idx_ " << idx() << " not valid\n";
1139                 return dummy;
1140         }
1141
1142         return cursor().cell();
1143 }
1144
1145
1146 MathXArray & MathCursor::xarray() const
1147 {
1148         return cursor().xcell();
1149 }
1150
1151
1152 void MathCursor::idxNext()
1153 {
1154         par()->idxNext(idx(), pos());
1155 }
1156
1157
1158 void MathCursor::idxPrev()
1159 {
1160         par()->idxPrev(idx(), pos());
1161 }
1162
1163
1164 void MathCursor::splitCell()
1165 {
1166         if (idx() == par()->nargs() - 1) 
1167                 return;
1168         MathArray ar = array();
1169         ar.erase(0, pos());
1170         array().erase(pos(), size());
1171         ++idx();
1172         pos() = 0;
1173         array().insert(0, ar);
1174 }
1175
1176
1177 void MathCursor::breakLine()
1178 {
1179         // leave inner cells
1180         while (popRight())
1181                 ;
1182
1183         MathMatrixInset * p = outerPar();
1184         if (p->getType() == LM_OT_SIMPLE || p->getType() == LM_OT_EQUATION) {
1185                 p->mutate(LM_OT_EQNARRAY);
1186                 idx() = 0;
1187                 pos() = size();
1188         } else {
1189                 p->addRow(row());
1190
1191                 // split line
1192                 const row_type r = row();
1193                 for (col_type c = col() + 1; c < p->ncols(); ++c) {
1194                         const MathMatrixInset::idx_type i1 = p->index(r, c);
1195                         const MathMatrixInset::idx_type i2 = p->index(r + 1, c);        
1196                         lyxerr << "swapping cells " << i1 << " and " << i2 << "\n";
1197                         p->cell(i1).swap(p->cell(i2));
1198                 }
1199
1200                 // split cell
1201                 splitCell();
1202                 p->cell(idx()).swap(p->cell(idx() + p->ncols() - 1));
1203         }
1204 }
1205
1206
1207 char MathCursor::valign() const
1208 {
1209         idx_type idx;
1210         MathArrayInset * p = enclosingArray(idx);
1211         return p ? p->valign() : '\0';
1212 }
1213
1214
1215 char MathCursor::halign() const
1216 {
1217         idx_type idx;
1218         MathArrayInset * p = enclosingArray(idx);
1219         return p ? p->halign(idx % p->ncols()) : '\0';
1220 }
1221
1222
1223 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1224 {
1225         MathCursorPos anc = normalAnchor();
1226         if (anc < cursor()) {
1227                 i1 = anc;
1228                 i2 = cursor();
1229         } else {
1230                 i1 = cursor();
1231                 i2 = anc;
1232         }
1233 }
1234
1235
1236 MathCursorPos & MathCursor::cursor()
1237 {
1238         return Cursor_.back();
1239 }
1240
1241
1242 MathCursorPos const & MathCursor::cursor() const
1243 {
1244         return Cursor_.back();
1245 }
1246
1247
1248 int MathCursor::cellXOffset() const
1249 {
1250         return par()->cellXOffset(idx());
1251 }
1252
1253
1254 int MathCursor::cellYOffset() const
1255 {
1256         return par()->cellYOffset(idx());
1257 }
1258
1259
1260 int MathCursor::xpos() const
1261 {
1262         return cellXOffset() + xarray().pos2x(pos(), inner());
1263 }
1264
1265
1266 int MathCursor::ypos() const
1267 {
1268         return cellYOffset();
1269 }
1270
1271
1272
1273 void MathCursor::gotoX(int x) 
1274 {
1275         pos() = xarray().x2pos(x - cellXOffset());
1276 }
1277
1278
1279 bool MathCursor::goUp()
1280 {
1281         // first ask the inset if it knows better then we
1282         if (par()->idxUp(idx(), pos()))
1283                 return true;
1284
1285         // leave subscript to the nearest side  
1286         if (par()->asScriptInset() && par()->asScriptInset()->down()) {
1287                 if (pos() <= size() / 2)
1288                         popLeft();
1289                 else
1290                         popRight();             
1291                 return true;
1292         }
1293
1294         // if not, apply brute force.
1295         int x0;
1296         int y0;
1297         getPos(x0, y0);
1298         std::vector<MathCursorPos> save = Cursor_;
1299         y0 -= xarray().ascent();
1300         for (int y = y0 - 4; y > outerPar()->yo() - outerPar()->ascent(); y -= 4) {
1301                 setPos(x0, y);
1302                 if (save != Cursor_ && xarray().yo() < y0)
1303                         return true;    
1304         }
1305         Cursor_ = save;
1306         return false;
1307 }
1308
1309
1310 bool MathCursor::goDown()
1311 {
1312         // first ask the inset if it knows better then we
1313         if (par()->idxDown(idx(), pos()))
1314                 return true;
1315
1316         // leave superscript to the nearest side        
1317         if (par()->asScriptInset() && par()->asScriptInset()->up()) {
1318                 if (pos() <= size() / 2)
1319                         popLeft();
1320                 else
1321                         popRight();             
1322                 return true;
1323         }
1324
1325         // if not, apply brute force.
1326         int x0;
1327         int y0;
1328         getPos(x0, y0);
1329         std::vector<MathCursorPos> save = Cursor_;
1330         y0 += xarray().descent();
1331         for (int y = y0 + 4; y < outerPar()->yo() + outerPar()->descent(); y += 4) {
1332                 setPos(x0, y);
1333                 if (save != Cursor_ && xarray().yo() > y0)
1334                         return true;    
1335         }
1336         Cursor_ = save;
1337         return false;
1338 }
1339
1340
1341 bool MathCursor::idxLeft()
1342 {
1343         return par()->idxLeft(idx(), pos());
1344 }
1345
1346
1347 bool MathCursor::idxRight()
1348 {
1349         return par()->idxRight(idx(), pos());
1350 }
1351
1352
1353 MathMatrixInset * MathCursor::outerPar() const
1354 {
1355         return
1356                 static_cast<MathMatrixInset *>(const_cast<MathInset *>(formula_->par()));
1357 }
1358
1359
1360 void MathCursor::interpret(string const & s)
1361 {
1362         //lyxerr << "interpret 1: '" << s << "'\n";
1363         //lyxerr << "in: " << in_word_set(s) << " \n";
1364
1365         if (s.empty())
1366                 return;
1367
1368         if (s.size() == 1) {
1369                 interpret(s[0]);
1370                 return;
1371         }
1372
1373         //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
1374         //owner_->getIntl()->getTrans().TranslateAndInsert(s[0], lt);   
1375         //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
1376
1377         if (s.size() > 7 && s.substr(0, 7) == "matrix ") {
1378                 unsigned int m = 1;
1379                 unsigned int n = 1;
1380                 string v_align;
1381                 string h_align;
1382                 istringstream is(s.substr(7).c_str());
1383                 is >> m >> n >> v_align >> h_align;
1384                 m = std::max(1u, m);
1385                 n = std::max(1u, n);
1386                 v_align += 'c';
1387                 MathArrayInset * p = new MathArrayInset(m, n);
1388                 p->valign(v_align[0]);
1389                 p->halign(h_align);
1390                 niceInsert(p);
1391                 return;
1392         }
1393
1394         if (s == "\\over" || s == "\\choose" || s == "\\atop") {
1395                 MathArray ar = array();
1396                 MathInset * p = createMathInset(s.substr(1));
1397                 p->cell(0).swap(array());
1398                 pos() = 0;
1399                 niceInsert(p);
1400                 popRight();
1401                 left();
1402                 return;
1403         }
1404
1405         niceInsert(createMathInset(s.substr(1)));
1406 }
1407
1408
1409 void MathCursor::interpret(char c)
1410 {
1411         //lyxerr << "interpret 2: '" << c << "'\n";
1412
1413         if (inMacroMode()) {
1414                 string name = macroName();
1415
1416                 if (name == "\\" && c == '#') {
1417                         insert(c, LM_TC_TEX);
1418                         return;
1419                 }
1420
1421                 if (name == "\\" && c == '\\') {
1422                         backspace();
1423                         interpret("\\backslash");
1424                         return;
1425                 }
1426
1427                 if (name == "\\#" && '1' <= c && c <= '9') {
1428                         insert(c, LM_TC_TEX);
1429                         macroModeClose();
1430                         return;
1431                 }
1432
1433                 if (isalpha(c)) {
1434                         insert(c, LM_TC_TEX);
1435                         return;
1436                 }
1437
1438                 if (name == "\\") {
1439                         insert(c, LM_TC_TEX);
1440                         macroModeClose();
1441                         return;
1442                 }
1443
1444                 macroModeClose();
1445                 return;
1446         }
1447
1448         // no macro mode
1449         if (c == '^' || c == '_') {
1450                 const bool up = (c == '^');
1451                 const bool in = inner();
1452                 selCut();
1453                 if (in)
1454                         ++pos();
1455                 if (!prevAtom())
1456                         insert(0);
1457                 MathInset * par = prevAtom()->ensure(up);
1458                 if (in)
1459                         pushLeft(par);
1460                 else
1461                         pushRight(par);
1462                 selPaste();
1463                 return;
1464         }
1465
1466         if (selection_)
1467                 selDel();
1468
1469         if (lastcode_ == LM_TC_TEXTRM) {
1470                 insert(c, LM_TC_TEXTRM);
1471                 return;
1472         }
1473
1474         if (c == ' ') {
1475                 MathSpaceInset * p = prevSpaceInset();
1476                 if (p) {
1477                         p->incSpace();
1478                         return;
1479                 }
1480
1481                 if (mathcursor->popRight())
1482                         return;
1483
1484 #warning look here
1485                         // this would not work if the inset is in an table!
1486                         //bv->text->cursorRight(bv, true);
1487                         //result = FINISHED;
1488                 return;
1489         }
1490
1491         if (strchr("{}", c)) {
1492                 insert(c, LM_TC_TEX);
1493                 return;
1494         }
1495
1496         if (strchr("#$%", c)) {
1497                 insert(new MathSpecialCharInset(c));    
1498                 lastcode_ = LM_TC_VAR;
1499                 return;
1500         }
1501
1502         if (isalpha(c) && (lastcode_ == LM_TC_GREEK || lastcode_ == LM_TC_GREEK1)) {
1503                 static char const greekl[][26] =
1504                         {"alpha", "beta", "chi", "delta", "epsilon", "phi",
1505                          "gamma", "eta", "iota", "iota", "kappa", "lambda", "mu",
1506                          "nu", "omikron", "pi", "omega", "rho", "sigma",
1507                          "tau", "upsilon", "theta", "omega", "xi", "upsilon", "zeta"};
1508                 static char const greeku[][26] =
1509                         {"Alpha", "Beta", "Chi", "Delta", "Epsilon", "Phi",
1510                          "Gamma", "Eta", "Iota", "Iota", "Kappa", "Lambda", "Mu",
1511                          "Nu", "Omikron", "Pi", "Omega", "Rho", "Sigma", "Tau",
1512                          "Upsilon", "Theta", "Omega", "xi", "Upsilon", "Zeta"};
1513         
1514                 latexkeys const * l = 0;        
1515                 if ('a' <= c && c <= 'z')
1516                         l = in_word_set(greekl[c - 'a']);
1517                 if ('A' <= c && c <= 'Z')
1518                         l = in_word_set(greeku[c - 'A']);
1519         
1520                 if (l)
1521                         insert(createMathInset(l));
1522                 else
1523                         insert(c, LM_TC_VAR);
1524
1525 #warning greek insert problem? look here!
1526                 if (lastcode_ == LM_TC_GREEK1)
1527                         lastcode_ = LM_TC_VAR;
1528                 return; 
1529         }
1530
1531         if (c == '\\') {
1532                 insert(c, LM_TC_TEX);
1533                 //bv->owner()->message(_("TeX mode"));
1534                 return; 
1535         }
1536
1537         // no special circumstances, so insert the character without any fuss
1538         insert(c, LM_TC_MIN);
1539 }
1540
1541
1542
1543 ////////////////////////////////////////////////////////////////////////
1544
1545
1546 bool operator==(MathCursorPos const & ti, MathCursorPos const & it)
1547 {
1548         return ti.par_ == it.par_ && ti.idx_ == it.idx_ && ti.pos_ == it.pos_;
1549 }
1550
1551
1552 bool operator<(MathCursorPos const & ti, MathCursorPos const & it)
1553 {
1554         if (ti.par_ != it.par_) {
1555                 lyxerr << "can't compare cursor and anchor in different insets\n";
1556                 return true;
1557         }
1558         if (ti.idx_ != it.idx_)
1559                 return ti.idx_ < it.idx_;
1560         return ti.pos_ < it.pos_;
1561 }
1562
1563
1564 MathArray & MathCursorPos::cell(MathCursor::idx_type idx) const
1565 {
1566         return par_->cell(idx);
1567 }
1568
1569
1570 MathArray & MathCursorPos::cell() const
1571 {
1572         return par_->cell(idx_);
1573 }
1574
1575
1576 MathXArray & MathCursorPos::xcell(MathCursor::idx_type idx) const
1577 {
1578         return par_->xcell(idx);
1579 }
1580
1581
1582 MathXArray & MathCursorPos::xcell() const
1583 {
1584         return par_->xcell(idx_);
1585 }
1586
1587
1588 MathAtom * MathCursorPos::at() const
1589 {
1590         return cell().at(pos_);
1591 }
1592
1593
1594 MathCursorPos MathCursor::normalAnchor() const
1595 {
1596         // use Anchor on the same level as Cursor
1597         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1598         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1599                 // anchor is behind cursor -> move anchor behind the inset
1600                 ++normal.pos_;
1601         }
1602         return normal;
1603 }
1604