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