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