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