]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
iterators for MathArray; cosmetics;
[lyx.git] / src / mathed / math_cursor.C
1 /*
2  *  File:        math_cursor.C
3  *  Purpose:     Interaction for mathed
4  *  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx>
5  *  Created:     January 1996
6  *  Description: Math interaction for a WYSIWYG math editor.
7  *
8  *  Dependencies: Xlib, XForms
9  *
10  *  Copyright: 1996, Alejandro Aguilar Sierra
11  *
12  *   Version: 0.8beta, Math & Lyx project.
13  *
14  *   You are free to use and modify this code under the terms of
15  *   the GNU General Public Licence version 2 or later.
16  */
17
18 #ifdef __GNUG__
19 #pragma implementation
20 #endif
21
22 #include <config.h>
23 #include <algorithm>
24 #include <cctype>
25
26 #include "debug.h"
27 #include "LColor.h"
28 #include "Painter.h"
29 #include "mathed/support.h"
30 #include "formulabase.h"
31 #include "math_cursor.h"
32 #include "math_arrayinset.h"
33 #include "math_bigopinset.h"
34 #include "math_symbolinset.h"
35 #include "math_decorationinset.h"
36 #include "math_deliminset.h"
37 #include "math_dotsinset.h"
38 #include "math_fracinset.h"
39 #include "math_funcinset.h"
40 #include "math_funcliminset.h"
41 #include "math_gridinset.h"
42 #include "math_macro.h"
43 #include "math_macroarg.h"
44 #include "math_macrotable.h"
45 #include "math_macrotemplate.h"
46 #include "math_matrixinset.h"
47 #include "math_rootinset.h"
48 #include "math_spaceinset.h"
49 #include "math_sqrtinset.h"
50 #include "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 MathTextCodes MathCursor::nextCode() const
865 {
866         return (pos() == size()) ? LM_TC_MIN : nextInset()->code();
867 }
868
869
870 void MathCursor::handleFont(MathTextCodes t)
871 {
872         if (selection_) {
873                 MathCursorPos i1;
874                 MathCursorPos i2;
875                 getSelection(i1, i2); 
876                 if (i1.idx_ == i2.idx_) {
877                         MathArray & ar = i1.cell();
878                         for (int pos = i1.pos_; pos != i2.pos_; ++pos) {
879                                 MathInset * p = ar.nextInset(pos);      
880                                 if (isalnum(p->getChar())) { 
881                                         MathTextCodes c = (p->code() == t) ? LM_TC_VAR : t;
882                                         p->code(c);
883                                 }
884                         }
885                 }
886         } else 
887                 lastcode_ = (lastcode_ == t) ? LM_TC_VAR : t;
888 }
889
890
891 void MathCursor::handleAccent(string const & name)
892 {
893         latexkeys const * l = in_word_set(name);
894         if (l)
895                 handleNest(new MathDecorationInset(l));
896 }
897
898
899 void MathCursor::handleDelim(int l, int r)
900 {
901         handleNest(new MathDelimInset(l, r));
902 }
903
904
905 void MathCursor::handleNest(MathInset * p)
906 {
907         if (selection_) {
908                 selCut();
909                 p->cell(0) = theSelection.glue();
910         }
911         insert(p);
912         pushRight(p);
913 }
914
915
916 void MathCursor::getPos(int & x, int & y)
917 {
918 #ifdef WITH_WARNINGS
919 #warning This should probably take cellXOffset and cellYOffset into account
920 #endif
921         x = xarray().xo() + xarray().pos2x(pos());
922         y = xarray().yo();
923 }
924
925
926 MathInset * MathCursor::par() const
927 {
928         return cursor().par_;
929 }
930
931
932 InsetFormulaBase const * MathCursor::formula()
933 {
934         return formula_;
935 }
936
937
938 int MathCursor::idx() const
939 {
940         return cursor().idx_;
941 }
942
943
944 int & MathCursor::idx()
945 {
946         return cursor().idx_;
947 }
948
949
950 int MathCursor::pos() const
951 {
952         return cursor().pos_;
953 }
954
955
956 int & MathCursor::pos()
957 {
958         return cursor().pos_;
959 }
960
961
962 bool MathCursor::inMacroMode() const
963 {
964         return imacro_;
965 }
966
967
968 bool MathCursor::selection() const
969 {
970         return selection_;
971 }
972
973
974 void MathCursor::clearLastCode()
975 {
976         lastcode_ = LM_TC_MIN;
977 }
978
979
980 void MathCursor::setLastCode(MathTextCodes t)
981 {
982         lastcode_ = t;
983 }
984
985
986 MathTextCodes MathCursor::getLastCode() const
987 {
988         return lastcode_;
989 }
990
991
992 MathArrayInset * MathCursor::enclosingArray(int & idx) const
993 {
994         for (int i = Cursor_.size() - 1; i >= 0; --i) {
995                 if (Cursor_[i].par_->isArray()) {
996                         idx = Cursor_[i].idx_;
997                         return static_cast<MathArrayInset *>(Cursor_[i].par_);
998                 }
999         }
1000         return 0;
1001 }
1002
1003
1004 void MathCursor::pullArg(bool goright)
1005 {
1006         // pullArg
1007         dump("pullarg");
1008         MathArray a = array();
1009         if (popLeft()) {
1010                 plainErase();
1011                 array().insert(pos(), a);
1012                 if (goright) 
1013                         pos() += a.size();
1014         }
1015 }
1016
1017
1018 MathStyles MathCursor::style() const
1019 {
1020         return xarray().style();
1021 }
1022
1023
1024 void MathCursor::normalize() const
1025 {
1026 #ifdef WITH_WARNINGS
1027 #warning This is evil!
1028 #endif
1029         MathCursor * it = const_cast<MathCursor *>(this);
1030
1031         if (idx() < 0)
1032                 lyxerr << "this should not really happen - 1: " << idx() << "\n";
1033         if (idx() >= par()->nargs()) {
1034                 lyxerr << "this should not really happen - 2: "
1035                        << idx() << " " << par()->nargs() << "\n";
1036                 dump("error 2");
1037         }
1038         it->idx()    = max(idx(), 0);
1039         it->idx()    = min(idx(), par()->nargs() - 1);
1040
1041         if (pos() < 0)
1042                 lyxerr << "this should not really happen - 3: " << pos() << "\n";
1043         if (pos() > size()) {
1044                 lyxerr << "this should not really happen - 4: "
1045                        << pos() << " " << size() << "\n";
1046                 dump("error 4");
1047         }
1048         it->pos() = max(pos(), 0);
1049         it->pos() = min(pos(), size());
1050 }
1051
1052
1053 int MathCursor::size() const
1054 {
1055         return array().size();
1056 }
1057
1058
1059 int MathCursor::col() const
1060 {
1061         return par()->col(idx());
1062 }
1063
1064
1065 int MathCursor::row() const
1066 {
1067         return par()->row(idx());
1068 }
1069
1070
1071 /*
1072 char MathCursorPos::getChar() const
1073 {
1074         return array().getChar(pos());
1075 }
1076
1077
1078 string MathCursorPos::readString()
1079 {
1080         string s;
1081         int code = nextCode();
1082         for ( ; OK() && nextCode() == code; Next()) 
1083                 s += getChar();
1084
1085         return s;
1086 }
1087 */
1088
1089
1090 MathInset * MathCursor::prevInset() const
1091 {
1092         normalize();
1093         if (!pos())
1094                 return 0;
1095         return array().nextInset(pos() - 1);
1096 }
1097
1098
1099 MathInset * MathCursor::nextInset() const
1100 {
1101         normalize();
1102         return array().nextInset(pos());
1103 }
1104
1105
1106 MathScriptInset * MathCursor::prevScriptInset() const
1107 {
1108         normalize();
1109         MathInset * p = prevInset();
1110         return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
1111 }
1112
1113
1114 MathSpaceInset * MathCursor::prevSpaceInset() const
1115 {
1116         normalize();
1117         MathInset * p = prevInset();
1118         return (p && p->isSpaceInset()) ? static_cast<MathSpaceInset *>(p) : 0;
1119 }
1120
1121
1122 MathArray & MathCursor::array() const
1123 {
1124         static MathArray dummy;
1125         if (!par()) {
1126                 lyxerr << "############  par_ not valid\n";
1127                 return dummy;
1128         }
1129
1130         if (idx() < 0 || idx() >= par()->nargs()) {
1131                 lyxerr << "############  idx_ " << idx() << " not valid\n";
1132                 return dummy;
1133         }
1134
1135         return cursor().cell();
1136 }
1137
1138
1139 MathXArray & MathCursor::xarray() const
1140 {
1141         return cursor().xcell();
1142 }
1143
1144
1145 void MathCursor::idxNext()
1146 {
1147         par()->idxNext(idx(), pos());
1148 }
1149
1150
1151 void MathCursor::idxPrev()
1152 {
1153         par()->idxPrev(idx(), pos());
1154 }
1155
1156
1157 void MathCursor::splitCell()
1158 {
1159         if (idx() == par()->nargs() - 1) 
1160                 return;
1161         MathArray ar = array();
1162         ar.erase(0, pos());
1163         array().erase(pos(), size());
1164         ++idx();
1165         pos() = 0;
1166         array().insert(0, ar);
1167 }
1168
1169
1170 void MathCursor::breakLine()
1171 {
1172         // leave inner cells
1173         while (popRight())
1174                 ;
1175
1176         MathMatrixInset * p = outerPar();
1177         if (p->getType() == LM_OT_SIMPLE || p->getType() == LM_OT_EQUATION) {
1178                 p->mutate(LM_OT_EQNARRAY);
1179                 idx() = 0;
1180                 pos() = size();
1181         } else {
1182                 p->addRow(row());
1183
1184                 // split line
1185                 const int r = row();
1186                 for (int c = col() + 1; c < p->ncols(); ++c) {
1187                         const int i1 = p->index(r, c);
1188                         const int i2 = p->index(r + 1, c);      
1189                         lyxerr << "swapping cells " << i1 << " and " << i2 << "\n";
1190                         p->cell(i1).swap(p->cell(i2));
1191                 }
1192
1193                 // split cell
1194                 splitCell();
1195                 p->cell(idx()).swap(p->cell(idx() + p->ncols() - 1));
1196         }
1197 }
1198
1199
1200 char MathCursor::valign() const
1201 {
1202         int idx;
1203         MathArrayInset * p = enclosingArray(idx);
1204         return p ? p->valign() : 0;
1205 }
1206
1207
1208 char MathCursor::halign() const
1209 {
1210         int idx;
1211         MathArrayInset * p = enclosingArray(idx);
1212         return p ? p->halign(idx % p->ncols()) : 0;
1213 }
1214
1215
1216 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1217 {
1218         MathCursorPos anc = normalAnchor();
1219         if (anc < cursor()) {
1220                 i1 = anc;
1221                 i2 = cursor();
1222         } else {
1223                 i1 = cursor();
1224                 i2 = anc;
1225         }
1226 }
1227
1228
1229 MathCursorPos & MathCursor::cursor()
1230 {
1231         return Cursor_.back();
1232 }
1233
1234
1235 MathCursorPos const & MathCursor::cursor() const
1236 {
1237         return Cursor_.back();
1238 }
1239
1240
1241 int MathCursor::cellXOffset() const
1242 {
1243         return par()->cellXOffset(idx());
1244 }
1245
1246
1247 int MathCursor::cellYOffset() const
1248 {
1249         return par()->cellYOffset(idx());
1250 }
1251
1252
1253 int MathCursor::xpos() const
1254 {
1255         return cellXOffset() + xarray().pos2x(pos());
1256 }
1257
1258
1259 int MathCursor::ypos() const
1260 {
1261         return cellYOffset();
1262 }
1263
1264
1265
1266 void MathCursor::gotoX(int x) 
1267 {
1268         pos() = xarray().x2pos(x - cellXOffset());
1269 }
1270
1271
1272 bool MathCursor::goUp()
1273 {
1274         // first ask the inset if it knows better then we
1275         if (par()->idxUp(idx(), pos()))
1276                 return true;
1277
1278         // if not, apply brute force.
1279         int x0;
1280         int y0;
1281         getPos(x0, y0);
1282         std::vector<MathCursorPos> save = Cursor_;
1283         y0 -= xarray().ascent();
1284         for (int y = y0 - 4; y > outerPar()->yo() - outerPar()->ascent(); y -= 4) {
1285                 setPos(x0, y);
1286                 if (save != Cursor_ && xarray().yo() < y0)
1287                         return true;    
1288         }
1289         Cursor_ = save;
1290         return false;
1291 }
1292
1293
1294 bool MathCursor::goDown()
1295 {
1296         // first ask the inset if it knows better then we
1297         if (par()->idxDown(idx(), pos()))
1298                 return true;
1299
1300         // if not, apply brute force.
1301         int x0;
1302         int y0;
1303         getPos(x0, y0);
1304         std::vector<MathCursorPos> save = Cursor_;
1305         y0 += xarray().descent();
1306         for (int y = y0 + 4; y < outerPar()->yo() + outerPar()->descent(); y += 4) {
1307                 setPos(x0, y);
1308                 if (save != Cursor_ && xarray().yo() > y0)
1309                         return true;    
1310         }
1311         Cursor_ = save;
1312         return false;
1313 }
1314
1315
1316 bool MathCursor::idxLeft()
1317 {
1318         return par()->idxLeft(idx(), pos());
1319 }
1320
1321
1322 bool MathCursor::idxRight()
1323 {
1324         return par()->idxRight(idx(), pos());
1325 }
1326
1327
1328 MathMatrixInset * MathCursor::outerPar() const
1329 {
1330         return
1331                 static_cast<MathMatrixInset *>(const_cast<MathInset *>(formula_->par()));
1332 }
1333
1334 ////////////////////////////////////////////////////////////////////////
1335
1336
1337 bool operator==(MathCursorPos const & ti, MathCursorPos const & it)
1338 {
1339         return ti.par_ == it.par_ && ti.idx_ == it.idx_ && ti.pos_ == it.pos_;
1340 }
1341
1342
1343 bool operator<(MathCursorPos const & ti, MathCursorPos const & it)
1344 {
1345         if (ti.par_ != it.par_) {
1346                 lyxerr << "can't compare cursor and anchor in different insets\n";
1347                 return true;
1348         }
1349         if (ti.idx_ != it.idx_)
1350                 return ti.idx_ < it.idx_;
1351         return ti.pos_ < it.pos_;
1352 }
1353
1354
1355 MathArray & MathCursorPos::cell(int idx) const
1356 {
1357         return par_->cell(idx);
1358 }
1359
1360 MathArray & MathCursorPos::cell() const
1361 {
1362         return par_->cell(idx_);
1363 }
1364
1365
1366 MathXArray & MathCursorPos::xcell(int idx) const
1367 {
1368         return par_->xcell(idx);
1369 }
1370
1371
1372 MathXArray & MathCursorPos::xcell() const
1373 {
1374         return par_->xcell(idx_);
1375 }
1376
1377
1378 MathCursorPos MathCursor::normalAnchor() const
1379 {
1380         // use Anchor on the same level as Cursor
1381         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1382         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1383                 // anchor is behind cursor -> move anchor behind the inset
1384                 ++normal.pos_;
1385         }
1386         return normal;
1387 }