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