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