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