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