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