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