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