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