]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
4ffe77a4f26421831fd0a2160c14fa409ffeb235
[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.empty())
606                 return;
607
608         if (s[0] == '^' || s[0] == '_') {
609                 bool const up = (s[0] == '^');
610                 selCut();       
611                 MathScriptInset * p = prevScriptInset();
612                 if (!p) {
613                         MathInset * b = prevInset();
614                         if (b && b->isScriptable()) {
615                                 p = new MathScriptInset(up, !up, b->clone());
616                                 plainLeft();
617                                 erase();
618                         } else {
619                                 p = new MathScriptInset(up, !up);
620                         }
621                         insert(p);
622                         plainLeft();
623                 }
624                 push(p, true);
625                 if (up)
626                         p->up(true);
627                 else
628                         p->down(true);
629                 cursor().idx_ = up ? 0 : 1;
630                 cursor().pos_ = 0;
631                 selPaste();
632                 return;
633         }
634
635         if (s[0] == '!' || s[0] == ','  || s[0] == ':' || s[0] == ';') {
636                 int sp = (s[0] == ',') ? 1:((s[0] == ':') ? 2:((s[0] == ';') ? 3: 0));
637                 insert(new MathSpaceInset(sp));
638                 return;
639         }
640
641         MathInset * p = 0;
642         latexkeys const * l = in_word_set(s);
643
644         if (l == 0) {
645                 if (s == "root") 
646                         p = new MathRootInset;
647                 else if (MathMacroTable::hasTemplate(s))
648                         p = new MathMacro(MathMacroTable::provideTemplate(s));
649                 else if (s.size() > 7 && s.substr(0, 7) == "matrix ") {
650                         int m = 1;
651                         int n = 1;
652                         string v_align;
653                         string h_align;
654                         istringstream is(s.substr(7).c_str());
655                         is >> m >> n >> v_align >> h_align;
656                         m = std::max(1, m);
657                         n = std::max(1, n);
658                         v_align += 'c';
659                         MathArrayInset * pp = new MathArrayInset(m, n);
660                         pp->valign(v_align[0]);
661                         pp->halign(h_align);
662                         p = pp;
663                 }
664                 else
665                         p = new MathFuncInset(s);
666         } else {
667                 switch (l->token) {
668                         case LM_TK_SYM: 
669                         case LM_TK_BIGSYM: 
670                         case LM_TK_FUNCLIM:
671                                 p = new MathBigopInset(l);
672                                 break;
673
674                         case LM_TK_STACK:
675                                 p = new MathFracInset("stackrel");
676                                 break;
677
678                         case LM_TK_FRAC:
679                                 p = new MathFracInset("frac");
680                                 break;
681
682                         case LM_TK_SQRT:
683                                 p = new MathSqrtInset;
684                                 break;
685
686                         case LM_TK_DECORATION:
687                                 p = new MathDecorationInset(l->name, l->id);
688                                 break;
689
690                         case LM_TK_SPACE:
691                                 p = new MathSpaceInset(l->id);
692                                 break;
693
694                         case LM_TK_DOTS:
695                                 p = new MathDotsInset(l->name, l->id);
696                                 break;
697
698                         case LM_TK_MACRO:
699                                 p = new MathMacro(MathMacroTable::provideTemplate(s));
700                                 break;
701
702                         default:
703                                 p = new MathFuncInset(l->name);
704                                 break;
705                 }
706         }
707
708         if (p) {
709                 bool oldsel = selection_;
710                 if (oldsel) 
711                         selCut();
712                 insert(p);
713                 if (p->nargs()) {
714                         plainLeft();
715                         right();  // do not push for e.g. MathBigopInset
716                         if (oldsel) 
717                                 selPaste();
718                 }
719                 p->metrics(p->size());
720         }
721 }
722
723
724 void MathCursor::macroModeOpen()
725 {
726         if (!imacro_) {
727                 imacro_ = new MathFuncInset("");
728                 array().insert(cursor().pos_, imacro_);
729                 array().next(cursor().pos_);
730                 //insert(imacro_);
731         } else
732                 lyxerr << "Math Warning: Already in macro mode" << endl;
733 }
734
735
736 void MathCursor::macroModeClose()
737 {
738         if (imacro_) {
739                 string name = imacro_->name();
740                 plainLeft();
741                 plainErase();
742                 imacro_ = 0;
743                 interpret(name);
744         }
745 }
746
747
748 void MathCursor::selCopy()
749 {
750         seldump("selCopy");
751         if (selection_) {
752                 theSelection.grab(*this);
753                 selClear();
754         }
755 }
756
757
758 void MathCursor::selCut()
759 {
760         seldump("selCut");
761         if (selection_) {
762                 theSelection.grab(*this);
763                 theSelection.erase(*this);
764                 selClear();
765         }
766 }
767
768
769 void MathCursor::selDel()
770 {
771         seldump("selDel");
772         if (selection_) {
773                 theSelection.erase(*this);
774                 selClear();
775         }
776 }
777
778
779 void MathCursor::selPaste()
780 {
781         seldump("selPaste");
782         theSelection.paste(*this);
783         selClear();
784 }
785
786
787 void MathCursor::selHandle(bool sel)
788 {
789         if (sel && !selection_)
790                 selStart();
791         if (!sel && selection_)
792                 selClear();
793 }
794
795
796 void MathCursor::selStart()
797 {
798         seldump("selStart");
799         if (selection_)
800                 return;
801
802         Anchor_ = Cursor_;
803         selection_ = true;
804 }
805
806
807 void MathCursor::selClear()
808 {
809         selection_ = false;
810 }
811
812
813 void MathCursor::drawSelection(Painter & pain) const
814 {
815         if (!selection_)
816                 return;
817
818         MathCursorPos i1;
819         MathCursorPos i2;
820         getSelection(i1, i2);
821
822         //lyxerr << "selection from: " << i1 << " to " << i2 << "\n";
823
824         if (i1.idx_ == i2.idx_) {
825                 MathXArray & c = i1.xcell();
826                 int x1 = c.xo() + c.pos2x(i1.pos_);
827                 int y1 = c.yo() - c.ascent();
828                 int x2 = c.xo() + c.pos2x(i2.pos_);
829                 int y2 = c.yo() + c.descent();
830                 pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
831         } else {
832
833                 std::vector<int> indices = i1.par_->idxBetween(i1.idx_, i2.idx_);
834                 for (unsigned i = 0; i < indices.size(); ++i) {
835                         MathXArray & c = i1.xcell(indices[i]);
836                         int x1 = c.xo();
837                         int y1 = c.yo() - c.ascent();
838                         int x2 = c.xo() + c.width();
839                         int y2 = c.yo() + c.descent();
840                         pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
841                 }
842         }
843 }
844
845
846 void MathCursor::handleFont(MathTextCodes t)
847 {
848         if (selection_) {
849                 MathCursorPos i1;
850                 MathCursorPos i2;
851                 getSelection(i1, i2); 
852                 if (i1.idx_ == i2.idx_) {
853                         MathArray & ar = i1.cell();
854                         for (int pos = i1.pos_; pos != i2.pos_; ar.next(pos))
855                                 if (!ar.isInset(pos) && isalnum(ar.getChar(pos))) { 
856                                         MathTextCodes c = ar.getCode(pos) == t ? LM_TC_VAR : t;
857                                         ar.setCode(pos, c);
858                                 }
859                 }
860         } else 
861                 lastcode_ = (lastcode_ == t) ? LM_TC_VAR : t;
862 }
863
864
865 void MathCursor::handleAccent(string const & name, int code)
866 {
867         MathDecorationInset * p = new MathDecorationInset(name, code);
868         if (selection_) {
869                 selCut();
870                 p->cell(0) = theSelection.glue();
871         }
872         insert(p);
873         push(p, true);
874 }
875
876
877 void MathCursor::handleDelim(int l, int r)
878 {
879         MathDelimInset * p = new MathDelimInset(l, r);
880         if (selection_) {
881                 selCut();
882                 p->cell(0) = theSelection.glue();
883         }
884         insert(p);
885         plainLeft();
886         push(p, true);
887 }
888
889
890 void MathCursor::getPos(int & x, int & y)
891 {
892         x = xarray().xo() + xarray().pos2x(cursor().pos_);
893         y = xarray().yo();
894 }
895
896
897 MathTextCodes MathCursor::nextCode() const
898 {
899         return array().getCode(cursor().pos_); 
900 }
901
902
903 MathTextCodes MathCursor::prevCode() const
904 {
905         return array().getCode(cursor().pos_ - 1); 
906 }
907
908
909 MathInset * MathCursor::par() const
910 {
911         return cursor().par_;
912 }
913
914
915 InsetFormulaBase const * MathCursor::formula()
916 {
917         return formula_;
918 }
919
920
921 int MathCursor::pos() const
922 {
923         return cursor().pos_;
924 }
925
926
927 bool MathCursor::inMacroMode() const
928 {
929         return imacro_;
930 }
931
932
933 bool MathCursor::selection() const
934 {
935         return selection_;
936 }
937
938
939 void MathCursor::clearLastCode()
940 {
941         lastcode_ = LM_TC_MIN;
942 }
943
944
945 void MathCursor::setLastCode(MathTextCodes t)
946 {
947         lastcode_ = t;
948 }
949
950
951 MathTextCodes MathCursor::getLastCode() const
952 {
953         return lastcode_;
954 }
955
956
957 MathInset * MathCursor::enclosing(MathInsetTypes t, int & idx) const
958 {
959         for (int i = Cursor_.size() - 1; i >= 0; --i) {
960                 //lyxerr << "checking level " << i << "\n";
961                 if (Cursor_[i].par_->getType() == t) {
962                         idx = Cursor_[i].idx_;
963                         return Cursor_[i].par_;
964                 }
965         }
966         return 0;
967 }
968
969
970 void MathCursor::pullArg(bool goright)
971 {
972         // pullArg
973         dump("pullarg");
974         MathArray a = array();
975         if (pop()) {
976                 plainErase();
977                 array().insert(cursor().pos_, a);
978                 if (goright) 
979                         cursor().pos_ += a.size();
980         }
981 }
982
983
984 MathStyles MathCursor::style() const
985 {
986         return xarray().style();
987 }
988
989
990 void MathCursor::normalize() const
991 {
992 #ifdef WITH_WARNINGS
993 #warning This is evil!
994 #endif
995         MathCursor * it = const_cast<MathCursor *>(this);
996
997         if (cursor().idx_ < 0 || cursor().idx_ > cursor().par_->nargs())
998                 lyxerr << "this should not really happen - 1\n";
999         it->cursor().idx_    = max(cursor().idx_, 0);
1000         it->cursor().idx_    = min(cursor().idx_, cursor().par_->nargs());
1001
1002         if (cursor().pos_ < 0 || cursor().pos_ > array().size())
1003                 lyxerr << "this should not really happen - 2\n";
1004         it->cursor().pos_ = max(cursor().pos_, 0);
1005         it->cursor().pos_ = min(cursor().pos_, array().size());
1006 }
1007
1008
1009 int MathCursor::col() const
1010 {
1011         return par()->col(cursor().idx_);
1012 }
1013
1014
1015 int MathCursor::row() const
1016 {
1017         return par()->row(cursor().idx_);
1018 }
1019
1020
1021 /*
1022 char MathCursorPos::getChar() const
1023 {
1024         return array().getChar(cursor().pos_);
1025 }
1026
1027
1028 string MathCursorPos::readString()
1029 {
1030         string s;
1031         int code = nextCode();
1032         for ( ; OK() && nextCode() == code; Next()) 
1033                 s += getChar();
1034
1035         return s;
1036 }
1037 */
1038
1039
1040 MathInset * MathCursor::prevInset() const
1041 {
1042         normalize();
1043         int c = cursor().pos_;
1044         if (!array().prev(c))
1045                 return 0;
1046         return array().nextInset(c);
1047 }
1048
1049
1050 MathInset * MathCursor::nextInset() const
1051 {
1052         normalize();
1053         return array().nextInset(cursor().pos_);
1054 }
1055
1056
1057 MathScriptInset * MathCursor::prevScriptInset() const
1058 {
1059         normalize();
1060         MathInset * p = array().prevInset(cursor().pos_);
1061         return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
1062 }
1063
1064
1065 MathSpaceInset * MathCursor::prevSpaceInset() const
1066 {
1067         normalize();
1068         MathInset * p = array().prevInset(cursor().pos_);
1069         return (p && p->isSpaceInset()) ? static_cast<MathSpaceInset *>(p) : 0;
1070 }
1071
1072
1073 MathArray & MathCursor::array() const
1074 {
1075         static MathArray dummy;
1076         if (!cursor().par_) {
1077                 lyxerr << "############  par_ not valid\n";
1078                 return dummy;
1079         }
1080
1081         if (cursor().idx_ < 0 || cursor().idx_ >= cursor().par_->nargs()) {
1082                 lyxerr << "############  idx_ " << cursor().idx_ << " not valid\n";
1083                 return dummy;
1084         }
1085
1086         return cursor().cell();
1087 }
1088
1089
1090 MathXArray & MathCursor::xarray() const
1091 {
1092         return cursor().xcell();
1093 }
1094
1095
1096 bool MathCursor::nextIsInset() const
1097 {
1098         return cursor().pos_ < array().size() && MathIsInset(nextCode());
1099 }
1100
1101
1102 bool MathCursor::prevIsInset() const
1103 {
1104         return cursor().pos_ > 0 && MathIsInset(prevCode());
1105 }
1106
1107
1108 int MathCursor::xpos() const 
1109 {
1110         normalize();
1111         return xarray().pos2x(cursor().pos_);
1112 }
1113
1114
1115 void MathCursor::gotoX(int x)
1116 {
1117         cursor().pos_ = xarray().x2pos(x);      
1118 }
1119
1120
1121 void MathCursor::idxNext()
1122 {
1123         cursor().par_->idxNext(cursor().idx_, cursor().pos_);
1124 }
1125
1126
1127 void MathCursor::idxPrev()
1128 {
1129         cursor().par_->idxPrev(cursor().idx_, cursor().pos_);
1130 }
1131
1132
1133 void MathCursor::splitCell()
1134 {
1135         if (cursor().idx_ == cursor().par_->nargs() - 1) 
1136                 return;
1137         MathArray ar = array();
1138         ar.erase(0, cursor().pos_);
1139         array().erase(cursor().pos_, array().size());
1140         ++cursor().idx_;
1141         cursor().pos_ = 0;
1142         array().insert(0, ar);
1143 }
1144
1145
1146 void MathCursor::breakLine()
1147 {
1148         MathMatrixInset * p = static_cast<MathMatrixInset *>(formula()->par());
1149         if (p->getType() == LM_OT_SIMPLE || p->getType() == LM_OT_EQUATION) {
1150                 p->mutate(LM_OT_EQNARRAY);
1151                 p->addRow(0);
1152                 cursor().idx_ = p->nrows();
1153                 cursor().pos_ = 0;
1154         } else {
1155                 p->addRow(row());
1156
1157                 // split line
1158                 const int r = row();
1159                 for (int c = col() + 1; c < p->ncols(); ++c) {
1160                         const int i1 = p->index(r, c);
1161                         const int i2 = p->index(r + 1, c);      
1162                         lyxerr << "swapping cells " << i1 << " and " << i2 << "\n";
1163                         p->cell(i1).swap(p->cell(i2));
1164                 }
1165
1166                 // split cell
1167                 splitCell();
1168                 p->cell(cursor().idx_).swap(p->cell(cursor().idx_ + p->ncols() - 1));
1169         }
1170 }
1171
1172
1173 char MathCursor::valign() const
1174 {
1175         int idx;
1176         MathGridInset * p =
1177                 static_cast<MathGridInset *>(enclosing(LM_OT_MATRIX, idx));
1178         return p ? p->valign() : 0;
1179 }
1180
1181
1182 char MathCursor::halign() const
1183 {
1184         int idx;
1185         MathGridInset * p =
1186                 static_cast<MathGridInset *>(enclosing(LM_OT_MATRIX, idx));
1187         return p ? p->halign(idx % p->ncols()) : 0;
1188 }
1189
1190
1191 MathCursorPos MathCursor::firstSelectionPos() const
1192 {
1193         MathCursorPos anc = normalAnchor();
1194         return anc < cursor() ? anc : cursor(); 
1195 }
1196
1197
1198 MathCursorPos MathCursor::lastSelectionPos() const
1199 {
1200         MathCursorPos anc = normalAnchor();
1201         return anc < cursor() ? cursor() : anc; 
1202 }
1203
1204
1205 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1206 {
1207         MathCursorPos anc = normalAnchor();
1208         if (anc < cursor()) {
1209                 i1 = anc;
1210                 i2 = cursor();
1211         } else {
1212                 i1 = cursor();
1213                 i2 = anc;
1214         }
1215 }
1216
1217
1218 MathCursorPos & MathCursor::cursor()
1219 {
1220         return Cursor_.back();
1221 }
1222
1223
1224 MathCursorPos const & MathCursor::cursor() const
1225 {
1226         return Cursor_.back();
1227 }
1228
1229
1230
1231 ////////////////////////////////////////////////////////////////////////
1232
1233
1234 bool operator==(MathCursorPos const & ti, MathCursorPos const & it)
1235 {
1236         return ti.par_ == it.par_ && ti.idx_ == it.idx_ && ti.pos_ == it.pos_;
1237 }
1238
1239
1240 bool operator<(MathCursorPos const & ti, MathCursorPos const & it)
1241 {
1242         if (ti.par_ != it.par_) {
1243                 lyxerr << "can't compare cursor and anchor in different insets\n";
1244                 return true;
1245         }
1246         if (ti.idx_ != it.idx_)
1247                 return ti.idx_ < it.idx_;
1248         return ti.pos_ < it.pos_;
1249 }
1250
1251
1252 MathArray & MathCursorPos::cell(int idx) const
1253 {
1254         return par_->cell(idx);
1255 }
1256
1257 MathArray & MathCursorPos::cell() const
1258 {
1259         return par_->cell(idx_);
1260 }
1261
1262
1263 MathXArray & MathCursorPos::xcell(int idx) const
1264 {
1265         return par_->xcell(idx);
1266 }
1267
1268
1269 MathXArray & MathCursorPos::xcell() const
1270 {
1271         return par_->xcell(idx_);
1272 }
1273
1274
1275 MathCursorPos MathCursor::normalAnchor() const
1276 {
1277         // use Anchor on the same level as Cursor
1278         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1279         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1280                 // anchor is behind cursor -> move anchor behind the inset
1281                 normal.cell().next(normal.pos_);
1282         }
1283         //lyxerr << "normalizing: from " << Anchor_[Anchor_.size() - 1] << " to "
1284         //      << normal << "\n";
1285         return normal;
1286 }
1287
1288
1289 bool MathCursorPos::idxUp()
1290 {
1291         return par_->idxUp(idx_, pos_);
1292 }
1293
1294
1295 bool MathCursorPos::idxDown()
1296 {
1297         return par_->idxDown(idx_, pos_);
1298 }
1299
1300
1301 bool MathCursorPos::idxLeft()
1302 {
1303         return par_->idxLeft(idx_, pos_);
1304 }
1305
1306
1307 bool MathCursorPos::idxRight()
1308 {
1309         return par_->idxRight(idx_, pos_);
1310 }