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