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