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