]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
re-enable automatic deletion of empty super/subscripts;
[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 1");
335         cursor_type best_cursor;
336         double best_dist = 1e10;
337
338         MathIterator it = ibegin(formula()->par().nucleus());
339         MathIterator et = iend(formula()->par().nucleus());
340         for ( ; it != et; ++it) {
341                 //lyxerr << "*it: " << *it << "  *et: " << *et << "\n";
342                 // avoid invalid nesting hen selecting
343                 if (selection_ && !positionable(it.cursor(), Anchor_))
344                         continue;
345                 //lyxerr << it.position() << endl;
346                 int xo = it.position().xpos();
347                 int yo = it.position().ypos();
348                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
349                 if (d < best_dist) {
350                         best_dist   = d;
351                         best_cursor = it.cursor();
352                 }
353         }
354         if (best_dist < 1e10)
355                 Cursor_ = best_cursor;
356         //lyxerr << "x: " << x << " y: " << y << " dist: " << best_dist << "\n";
357         lyx::Assert(Cursor_.size());
358         dump("setPos 2");
359 }
360
361
362
363 void MathCursor::home(bool sel)
364 {
365         dump("home 1");
366         selHandle(sel);
367         macroModeClose();
368         lastcode_ = LM_TC_VAR;
369         if (!par()->idxHome(idx(), pos())) 
370                 popLeft();
371         dump("home 2");
372 }
373
374
375 void MathCursor::end(bool sel)
376 {
377         dump("end 1");
378         selHandle(sel);
379         macroModeClose();
380         lastcode_ = LM_TC_VAR;
381         if (!par()->idxEnd(idx(), pos()))
382                 popRight();
383         dump("end 2");
384 }
385
386
387 void MathCursor::plainErase()
388 {
389         array().erase(pos());
390 }
391
392
393 void MathCursor::plainInsert(MathAtom const & t)
394 {
395         array().insert(pos(), t);
396         ++pos();
397 }
398
399
400 void MathCursor::insert(char c, MathTextCodes t)
401 {
402         //lyxerr << "inserting '" << c << "'\n";
403         plainInsert(MathAtom(new MathCharInset(c, t)));
404 }
405
406
407 void MathCursor::insert(MathAtom const & t)
408 {
409         macroModeClose();
410
411         if (selection_) {
412                 if (t->nargs())
413                         selCut();
414                 else
415                         selDel();
416         }
417
418         plainInsert(t);
419 }
420
421
422 void MathCursor::niceInsert(MathAtom const & t) 
423 {
424         selCut();
425         insert(t); // inserting invalidates the pointer!
426         MathAtom const & p = prevAtom();
427         if (p->nargs()) {
428                 posLeft();
429                 right();  // do not push for e.g. MathSymbolInset
430                 selPaste();
431         }
432 }
433
434
435 void MathCursor::insert(MathArray const & ar)
436 {
437         macroModeClose();
438         if (selection_)
439                 selCut();
440
441         array().insert(pos(), ar);
442         pos() += ar.size();
443 }
444
445
446 void MathCursor::paste(MathArray const & ar)
447 {
448         Anchor_ = Cursor_;
449         selection_ = true;
450         array().insert(pos(), ar);
451         pos() += ar.size();
452 }
453
454
455 void MathCursor::backspace()
456 {
457         if (pos() == 0) {
458                 pullArg(false);
459                 return;
460         }       
461
462         if (selection_) {
463                 selDel();
464                 return;
465         }
466
467         MathScriptInset * p = prevAtom()->asScriptInset();
468         if (p) {
469                 p->removeScript(p->hasUp());
470                 // Don't delete if there is anything left 
471                 if (p->hasUp() || p->hasDown())
472                         return;
473         }
474
475         --pos();
476         plainErase();
477 }
478
479
480 void MathCursor::erase()
481 {
482         if (inMacroMode())
483                 return;
484
485         if (selection_) {
486                 selDel();
487                 return;
488         }
489
490         // delete empty cells if necessary
491         if (array().empty()) {
492                 bool popit;
493                 bool removeit;
494                 par()->idxDelete(idx(), popit, removeit);
495                 if (popit && popLeft() && removeit)
496                         plainErase();
497                 return;
498         }
499
500         if (pos() == size())
501                 return;
502
503         MathScriptInset * p = nextAtom()->asScriptInset();
504         if (p) {
505                 p->removeScript(p->hasUp());
506                 // Don't delete if there is anything left 
507                 if (p->hasUp() || p->hasDown())
508                         return;
509         }
510
511         plainErase();
512 }
513
514
515 void MathCursor::delLine()
516 {
517         macroModeClose();
518
519         if (selection_) {
520                 selDel();
521                 return;
522         }
523
524         if (par()->nrows() > 1) {
525                 // grid are the only things with more than one row...
526                 lyx::Assert(par()->asGridInset());
527                 par()->asGridInset()->delRow(hullRow());
528         }
529
530         if (idx() > par()->nargs())
531                 idx() = par()->nargs();
532
533         if (pos() > size())
534                 pos() = size();
535 }
536
537
538 bool MathCursor::up(bool sel)
539 {
540         dump("up 1");
541         macroModeClose();
542         selHandle(sel);
543
544         if (!selection_) {
545                 MathInset::idx_type i = 0;
546                 MathInset::pos_type p = 0;
547
548                 // check whether we could move into the inset
549                 if (hasPrevAtom() && prevAtom()->idxLastUp(i, p)) {
550                         pushRight(prevAtom());
551                         idx() = i;
552                         pos() = p;
553                         return true;
554                 }
555
556                 if (hasNextAtom() && nextAtom()->idxFirstUp(i, p)) {
557                         pushLeft(nextAtom());
558                         idx() = i;
559                         pos() = p;
560                         return true;
561                 }
562         }
563
564         cursor_type save = Cursor_;
565         if (goUpDown(true))
566                 return true;
567         Cursor_ = save;
568         return selection_;
569 }
570
571
572 bool MathCursor::down(bool sel)
573 {
574         dump("down 1");
575         macroModeClose();
576         selHandle(sel);
577
578         if (!selection_) {
579                 MathInset::idx_type i = 0;
580                 MathInset::pos_type p = 0;
581
582                 // check whether we could move into the inset
583                 if (hasPrevAtom() && prevAtom()->idxLastDown(i, p)) {
584                         pushRight(prevAtom());
585                         idx() = i;
586                         pos() = p;
587                         return true;
588                 }
589
590                 if (hasNextAtom() && nextAtom()->idxFirstDown(i, p)) {
591                         pushLeft(nextAtom());
592                         idx() = i;
593                         pos() = p;
594                         return true;
595                 }
596         }
597
598         cursor_type save = Cursor_;
599         if (goUpDown(false))
600                 return true;
601         Cursor_ = save;
602         return selection_;
603 }
604
605
606 bool MathCursor::toggleLimits()
607 {
608         if (!hasNextAtom())
609                 return false;
610         MathScriptInset * t = nextAtom()->asScriptInset();
611         if (!t)
612                 return false;
613         int old = t->limits();
614         t->limits(old < 0 ? 1 : -1);
615         return old != t->limits();
616 }
617
618
619 void MathCursor::macroModeClose()
620 {
621         string s = macroName();
622         if (s.size()) {
623                 size_type old = pos();
624                 pos() -= s.size();
625                 array().erase(pos(), old);
626                 interpret(s);
627         }
628 }
629
630
631 int MathCursor::macroNamePos() const
632 {
633         for (int i = pos() - 1; i >= 0; --i) { 
634                 MathAtom & p = array().at(i);
635                 if (p->code() == LM_TC_TEX && p->getChar() == '\\')
636                         return i;
637         }
638         return -1;
639 }
640
641
642 string MathCursor::macroName() const
643 {
644         string s;
645         for (int i = macroNamePos(); i >= 0 && i < int(pos()); ++i) 
646                 s += array().at(i)->getChar();
647         return s;
648 }
649
650
651 void MathCursor::selCopy()
652 {
653         dump("selCopy");
654         if (selection_) {
655                 theSelection.grab(*this);
656                 selClear();
657         }
658 }
659
660
661 void MathCursor::selCut()
662 {
663         dump("selCut");
664         if (selection_) {
665                 theSelection.grab(*this);
666                 theSelection.erase(*this);
667                 selClear();
668         } else {
669                 theSelection.clear();
670         }
671 }
672
673
674 void MathCursor::selDel()
675 {
676         dump("selDel");
677         if (selection_) {
678                 theSelection.erase(*this);
679                 if (pos() > size())
680                         pos() = size();
681                 selClear();
682         }
683 }
684
685
686 void MathCursor::selPaste()
687 {
688         dump("selPaste");
689         theSelection.paste(*this);
690         //theSelection.grab(*this);
691         //selClear();
692 }
693
694
695 void MathCursor::selHandle(bool sel)
696 {
697         if (sel == selection_)
698                 return;
699         //theSelection.clear();
700         Anchor_    = Cursor_;
701         selection_ = sel;
702 }
703
704
705 void MathCursor::selStart()
706 {
707         dump("selStart 1");
708         //theSelection.clear();
709         Anchor_ = Cursor_;
710         selection_ = true;
711         dump("selStart 2");
712 }
713
714
715 void MathCursor::selClear()
716 {
717         dump("selClear 1");
718         selection_ = false;
719         dump("selClear 2");
720 }
721
722
723 void MathCursor::selGet(MathArray & ar)
724 {
725         dump("selGet");
726         if (!selection_)
727                 return;
728
729         theSelection.grab(*this);
730         ar = theSelection.glue();
731 }
732
733
734
735 void MathCursor::drawSelection(Painter & pain) const
736 {
737         if (!selection_)
738                 return;
739
740         MathCursorPos i1;
741         MathCursorPos i2;
742         getSelection(i1, i2);
743
744         if (i1.idx_ == i2.idx_) {
745                 MathXArray & c = i1.xcell();
746                 int x1 = c.xo() + c.pos2x(i1.pos_);
747                 int y1 = c.yo() - c.ascent();
748                 int x2 = c.xo() + c.pos2x(i2.pos_);
749                 int y2 = c.yo() + c.descent();
750                 pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
751         } else {
752                 std::vector<MathInset::idx_type> indices
753                         = i1.par_->idxBetween(i1.idx_, i2.idx_);
754                 for (unsigned i = 0; i < indices.size(); ++i) {
755                         MathXArray & c = i1.xcell(indices[i]);
756                         int x1 = c.xo();
757                         int y1 = c.yo() - c.ascent();
758                         int x2 = c.xo() + c.width();
759                         int y2 = c.yo() + c.descent();
760                         pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
761                 }
762         }
763
764 #if 0
765         // draw anchor if different from selection boundary
766         MathCursorPos anc = Anchor_.back();
767         if (anc != i1 && anc != i2) {
768                 MathXArray & c = anc.xcell();
769                 int x  = c.xo() + c.pos2x(anc.pos_);
770                 int y1 = c.yo() - c.ascent();
771                 int y2 = c.yo() + c.descent();
772                 pain.line(x, y1, x, y2, LColor::math);
773         }
774 #endif
775 }
776
777
778 void MathCursor::handleFont(MathTextCodes t)
779 {
780         macroModeClose();
781         if (selection_) {
782                 MathCursorPos i1;
783                 MathCursorPos i2;
784                 getSelection(i1, i2); 
785                 if (i1.idx_ == i2.idx_) {
786                         MathArray & ar = i1.cell();
787                         for (MathInset::pos_type pos = i1.pos_; pos != i2.pos_; ++pos)
788                                 ar.at(pos)->handleFont(t);
789                 }
790         } else 
791                 lastcode_ = (lastcode_ == t) ? LM_TC_VAR : t;
792 }
793
794
795 void MathCursor::handleDelim(string const & l, string const & r)
796 {
797         handleNest(new MathDelimInset(l, r));
798 }
799
800
801 void MathCursor::handleNest(MathInset * p)
802 {
803         if (selection_) {
804                 selCut();
805                 p->cell(0) = theSelection.glue();
806         }
807         insert(MathAtom(p)); // this invalidates p!
808         pushRight(prevAtom());
809 }
810
811
812 void MathCursor::getPos(int & x, int & y)
813 {
814 #ifdef WITH_WARNINGS
815 #warning This should probably take cellXOffset and cellYOffset into account
816 #endif
817         x = xarray().xo() + xarray().pos2x(pos());
818         y = xarray().yo();
819 }
820
821
822 MathInset * MathCursor::par() const
823 {
824         return cursor().par_;
825 }
826
827
828 InsetFormulaBase * MathCursor::formula()
829 {
830         return formula_;
831 }
832
833
834 MathCursor::idx_type MathCursor::idx() const
835 {
836         return cursor().idx_;
837 }
838
839
840 MathCursor::idx_type & MathCursor::idx()
841 {
842         return cursor().idx_;
843 }
844
845
846 MathCursor::pos_type MathCursor::pos() const
847 {
848         return cursor().pos_;
849 }
850
851
852 MathCursor::pos_type & MathCursor::pos()
853 {
854         return cursor().pos_;
855 }
856
857
858 bool MathCursor::inMacroMode() const
859 {
860         return macroNamePos() != -1;
861 }
862
863
864 bool MathCursor::selection() const
865 {
866         return selection_;
867 }
868
869
870 MathGridInset * MathCursor::enclosingGrid(MathCursor::idx_type & idx) const
871 {
872         for (int i = Cursor_.size() - 1; i >= 0; --i) {
873                 MathGridInset * p = Cursor_[i].par_->asGridInset();
874                 if (p) {
875                         idx = Cursor_[i].idx_;
876                         return p;
877                 }
878         }
879         return 0;
880 }
881
882
883 void MathCursor::pullArg(bool goright)
884 {
885         dump("pullarg");
886         MathArray a = array();
887
888         MathScriptInset const * p = par()->asScriptInset();
889         if (p) {
890                 // special handling for scripts
891                 const bool up = p->hasUp();
892                 popLeft();
893                 MathScriptInset * q = nextAtom()->asScriptInset();
894                 if (q)
895                         q->removeScript(up);
896                 ++pos();
897                 array().insert(pos(), a);
898                 return;
899         }
900
901         if (popLeft()) {
902                 plainErase();
903                 array().insert(pos(), a);
904                 if (goright) 
905                         pos() += a.size();
906         }
907 }
908
909
910 void MathCursor::normalize() const
911 {
912 #ifdef WITH_WARNINGS
913 #warning This is evil!
914 #endif
915         MathCursor * it = const_cast<MathCursor *>(this);
916
917         if (idx() >= par()->nargs()) {
918                 lyxerr << "this should not really happen - 1: "
919                        << idx() << " " << par()->nargs() << "\n";
920                 dump("error 2");
921         }
922         it->idx() = min(idx(), par()->nargs() - 1);
923
924         if (pos() > size()) {
925                 lyxerr << "this should not really happen - 2: "
926                         << pos() << " " << size() <<  " in idx: " << it->idx()
927                         << " in atom: '";
928                 WriteStream wi(lyxerr, false);
929                 it->par()->write(wi);
930                 lyxerr << "\n";
931                 dump("error 4");
932         }
933         it->pos() = min(pos(), size());
934 }
935
936
937 MathCursor::size_type MathCursor::size() const
938 {
939         return array().size();
940 }
941
942
943 MathCursor::col_type MathCursor::hullCol() const
944 {
945         return Cursor_[0].par_->asGridInset()->col(Cursor_[0].idx_);
946 }
947
948
949 MathCursor::row_type MathCursor::hullRow() const
950 {
951         return Cursor_[0].par_->asGridInset()->row(Cursor_[0].idx_);
952 }
953
954
955 bool MathCursor::hasPrevAtom() const
956 {
957         return pos() > 0;
958 }
959
960
961 bool MathCursor::hasNextAtom() const
962 {
963         return pos() < size();
964 }
965
966
967 MathAtom const & MathCursor::prevAtom() const
968 {
969         lyx::Assert(pos() > 0);
970         return array().at(pos() - 1);
971 }
972
973
974 MathAtom & MathCursor::prevAtom()
975 {
976         lyx::Assert(pos() > 0);
977         return array().at(pos() - 1);
978 }
979
980
981 MathAtom const & MathCursor::nextAtom() const
982 {
983         lyx::Assert(pos() < size());
984         return array().at(pos());
985 }
986
987
988 MathAtom & MathCursor::nextAtom()
989 {
990         lyx::Assert(pos() < size());
991         return array().at(pos());
992 }
993
994
995 MathArray & MathCursor::array() const
996 {
997         static MathArray dummy;
998
999         if (idx() >= par()->nargs()) {
1000                 lyxerr << "############  idx_ " << idx() << " not valid\n";
1001                 return dummy;
1002         }
1003
1004         if (Cursor_.size() == 0) {
1005                 lyxerr << "############  Cursor_.size() == 0 not valid\n";
1006                 return dummy;
1007         }
1008
1009         return cursor().cell();
1010 }
1011
1012
1013 MathXArray & MathCursor::xarray() const
1014 {
1015         static MathXArray dummy;
1016
1017         if (Cursor_.size() == 0) {
1018                 lyxerr << "############  Cursor_.size() == 0 not valid\n";
1019                 return dummy;
1020         }
1021
1022         return cursor().xcell();
1023 }
1024
1025
1026 void MathCursor::idxNext()
1027 {
1028         par()->idxNext(idx(), pos());
1029 }
1030
1031
1032 void MathCursor::idxPrev()
1033 {
1034         par()->idxPrev(idx(), pos());
1035 }
1036
1037
1038 void MathCursor::splitCell()
1039 {
1040         if (idx() + 1 == par()->nargs()) 
1041                 return;
1042         MathArray ar = array();
1043         ar.erase(0, pos());
1044         array().erase(pos(), size());
1045         ++idx();
1046         pos() = 0;
1047         array().insert(0, ar);
1048 }
1049
1050
1051 void MathCursor::breakLine()
1052 {
1053         // leave inner cells
1054         while (popRight())
1055                 ;
1056
1057         MathHullInset * p = formula()->par()->asHullInset();
1058         if (!p)
1059                 return;
1060
1061         if (p->getType() == LM_OT_SIMPLE || p->getType() == LM_OT_EQUATION) {
1062                 p->mutate(LM_OT_EQNARRAY);
1063                 idx() = 0;
1064                 pos() = size();
1065         } else {
1066                 p->addRow(hullRow());
1067
1068                 // split line
1069                 const row_type r = hullRow();
1070                 for (col_type c = hullCol() + 1; c < p->ncols(); ++c)
1071                         p->cell(p->index(r, c)).swap(p->cell(p->index(r + 1, c)));
1072
1073                 // split cell
1074                 splitCell();
1075                 p->cell(idx()).swap(p->cell(idx() + p->ncols() - 1));
1076         }
1077 }
1078
1079
1080 //void MathCursor::readLine(MathArray & ar) const
1081 //{
1082 //      idx_type base = row() * par()->ncols();
1083 //      for (idx_type off = 0; off < par()->ncols(); ++off)
1084 //              ar.push_back(par()->cell(base + off));
1085 //}
1086
1087
1088 char MathCursor::valign() const
1089 {
1090         idx_type idx;
1091         MathGridInset * p = enclosingGrid(idx);
1092         return p ? p->valign() : '\0';
1093 }
1094
1095
1096 char MathCursor::halign() const
1097 {
1098         idx_type idx;
1099         MathGridInset * p = enclosingGrid(idx);
1100         return p ? p->halign(idx % p->ncols()) : '\0';
1101 }
1102
1103
1104 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1105 {
1106         MathCursorPos anc = normalAnchor();
1107         if (anc < cursor()) {
1108                 i1 = anc;
1109                 i2 = cursor();
1110         } else {
1111                 i1 = cursor();
1112                 i2 = anc;
1113         }
1114 }
1115
1116
1117 MathCursorPos & MathCursor::cursor()
1118 {
1119         lyx::Assert(Cursor_.size());
1120         return Cursor_.back();
1121 }
1122
1123
1124 MathCursorPos const & MathCursor::cursor() const
1125 {
1126         lyx::Assert(Cursor_.size());
1127         return Cursor_.back();
1128 }
1129
1130
1131 bool MathCursor::goUpDown(bool up)
1132 {
1133         int xo, yo;
1134         getPos(xo, yo);
1135
1136         // try to find an inset that knows better then we
1137         while (1) {
1138                 // we found a cell that think something "below" us.
1139                 if (up) {
1140                         if (par()->idxUp(idx()))
1141                                 break;
1142                 } else {
1143                         if (par()->idxDown(idx()))
1144                                 break;
1145                 }
1146
1147                 if (!popLeft()) {
1148                         // have reached hull
1149                         return
1150                                 bruteFind(xo, yo,
1151                                         formula()->xlow(),
1152                                         formula()->xhigh(),
1153                                         up ? formula()->ylow() : yo + 4,
1154                                         up ? yo - 4 : formula()->yhigh()
1155                                 );
1156                 }
1157         }
1158         int xlow, xhigh, ylow, yhigh;
1159         xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1160         bruteFind(xo, yo, xlow, xhigh, ylow, yhigh);
1161         return true;
1162 }
1163
1164
1165 bool MathCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1166 {
1167         //lyxerr << "looking at range: "
1168         //      << "[" << xlow << "..." << xhigh << "]" 
1169         //      << " x [" << ylow << "..." << yhigh << "]"
1170         //      << "   xo: " << x << "  yo: " << y << "\n";
1171
1172         cursor_type best_cursor;
1173         double best_dist = 1e10;
1174
1175         MathIterator it = ibegin(formula()->par().nucleus());
1176         MathIterator et = iend(formula()->par().nucleus());
1177         for ( ; it != et; ++it) {
1178                 int xo = it.position().xpos();
1179                 int yo = it.position().ypos();
1180                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1181                         double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1182                         if (d < best_dist) {
1183                                 best_dist   = d;
1184                                 best_cursor = it.cursor();
1185                         }
1186                 }
1187         }
1188         if (best_dist < 1e10)
1189                 Cursor_ = best_cursor;
1190         return best_dist < 1e10;
1191 }
1192
1193
1194 bool MathCursor::idxLeft()
1195 {
1196         return par()->idxLeft(idx(), pos());
1197 }
1198
1199
1200 bool MathCursor::idxRight()
1201 {
1202         return par()->idxRight(idx(), pos());
1203 }
1204
1205
1206 bool MathCursor::interpret(string const & s)
1207 {
1208         //lyxerr << "interpret 1: '" << s << "'\n";
1209         if (s.empty())
1210                 return true;
1211
1212         if (s.size() == 1)
1213                 return interpret(s[0]);
1214
1215         //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
1216         //owner_->getIntl()->getTrans().TranslateAndInsert(s[0], lt);   
1217         //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
1218
1219         if (s.size() >= 5 && s.substr(0, 5) == "cases") {
1220                 unsigned int n = 1;
1221                 istringstream is(s.substr(5).c_str());
1222                 is >> n;
1223                 n = std::max(1u, n);
1224                 niceInsert(MathAtom(new MathCasesInset(n)));
1225                 return true;
1226         }
1227
1228         if (s.size() >= 6 && s.substr(0, 6) == "matrix") {
1229                 unsigned int m = 1;
1230                 unsigned int n = 1;
1231                 string v_align;
1232                 string h_align;
1233                 istringstream is(s.substr(6).c_str());
1234                 is >> m >> n >> v_align >> h_align;
1235                 m = std::max(1u, m);
1236                 n = std::max(1u, n);
1237                 v_align += 'c';
1238                 niceInsert(MathAtom(new MathArrayInset(m, n, v_align[0], h_align)));
1239                 return true;
1240         }
1241
1242         if (s.size() >= 7 && s.substr(0, 7) == "replace") {
1243                 ReplaceData rep;
1244                 istringstream is(s.substr(7).c_str());
1245                 string from, to;
1246                 is >> from >> to;
1247                 mathed_parse_cell(rep.from, from);
1248                 mathed_parse_cell(rep.to, to);
1249                 lyxerr << "replacing '" << from << "' with '" << to << "'\n";
1250                 par()->replace(rep);
1251                 return true;
1252         }
1253
1254         if (s == "\\over" || s == "\\choose" || s == "\\atop") {
1255                 MathArray ar = array();
1256                 MathAtom t = createMathInset(s.substr(1));
1257                 t->asNestInset()->cell(0).swap(array());
1258                 pos() = 0;
1259                 niceInsert(t);
1260                 popRight();
1261                 left();
1262                 return true;
1263         }
1264
1265         latexkeys const * l = in_word_set(s.substr(1));
1266         if (l && (l->token == LM_TK_FONT || l->token == LM_TK_OLDFONT)) {
1267                 lastcode_ = static_cast<MathTextCodes>(l->id);
1268                 return true;
1269         }
1270
1271         niceInsert(createMathInset(s.substr(1)));
1272         return true;
1273 }
1274
1275
1276 bool MathCursor::interpret(char c)
1277 {
1278         //lyxerr << "interpret 2: '" << c << "'\n";
1279         if (c == '^' || c == '_') {
1280                 macroModeClose();
1281                 const bool up = (c == '^');
1282                 selCut();
1283                 if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1284                         prevAtom()->asScriptInset()->ensure(up);
1285                         pushRight(prevAtom());
1286                         idx() = up;
1287                         pos() = size();
1288                 } else if (hasNextAtom() && nextAtom()->asScriptInset()) {
1289                         nextAtom()->asScriptInset()->ensure(up);
1290                         pushLeft(nextAtom());
1291                         idx() = up;
1292                         pos() = 0;
1293                 } else {
1294                         plainInsert(MathAtom(new MathScriptInset(up)));
1295                         prevAtom()->asScriptInset()->ensure(up);
1296                         pushRight(prevAtom());
1297                         idx() = up;
1298                         pos() = 0;
1299                 }
1300                 selPaste();
1301                 dump("1");
1302                 return true;
1303         }
1304
1305
1306         // handle macroMode
1307         if (inMacroMode()) {
1308                 string name = macroName();
1309
1310                 if (name == "\\" && c == '#') {
1311                         insert(c, LM_TC_TEX);
1312                         return true;
1313                 }
1314
1315                 if (name == "\\" && c == '\\') {
1316                         backspace();
1317                         interpret("\\backslash");
1318                         return true;
1319                 }
1320
1321                 if (name == "\\#" && '1' <= c && c <= '9') {
1322                         insert(c, LM_TC_TEX);
1323                         macroModeClose();
1324                         return true;
1325                 }
1326
1327                 if (isalpha(c)) {
1328                         insert(c, LM_TC_TEX);
1329                         return true;
1330                 }
1331
1332                 if (name == "\\") {
1333                         insert(c, LM_TC_TEX);
1334                         macroModeClose();
1335                         return true;
1336                 }
1337
1338                 macroModeClose();
1339                 return true;
1340         }
1341
1342         if (selection_)
1343                 selClear();
1344
1345         if (lastcode_ == LM_TC_TEXTRM) {
1346                 // suppress direct insertion of to spaces in a row
1347                 // the still allows typing  '<space>a<space>' and deleting the 'a', but
1348                 // it is better than nothing
1349                 if (c == ' ' && hasPrevAtom() && prevAtom()->getChar() == ' ')
1350                         return true;
1351                 insert(c, LM_TC_TEXTRM);
1352                 return true;
1353         }
1354
1355         if (c == ' ') {
1356                 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1357                         prevAtom()->asSpaceInset()->incSpace();
1358                         return true;
1359                 }
1360         
1361                 if (mathcursor->popRight())
1362                         return true;
1363
1364                 // if are at the very end, leave the formula
1365                 return pos() != size();
1366         }
1367
1368 /*
1369         if (strchr("{}", c)) {
1370                 insert(c, LM_TC_TEX);
1371                 return true;
1372         }
1373 */
1374
1375         if (c == '{') {
1376                 niceInsert(MathAtom(new MathBraceInset));
1377                 return true;
1378         }
1379
1380         if (c == '}') {
1381                 return true;
1382         }
1383
1384         if (strchr("#$%", c)) {
1385                 insert(MathAtom(new MathSpecialCharInset(c)));  
1386                 lastcode_ = LM_TC_VAR;
1387                 return true;
1388         }
1389
1390         if (isalpha(c) && lastcode_ == LM_TC_GREEK) {
1391                 insert(c, LM_TC_VAR);
1392                 return true;
1393         }
1394
1395         if (isalpha(c) && lastcode_ == LM_TC_GREEK1) {
1396                 insert(c, LM_TC_VAR);
1397                 lastcode_ = LM_TC_VAR;
1398                 return true;
1399         }
1400
1401         if (c == '\\') {
1402                 insert(c, LM_TC_TEX);
1403                 //bv->owner()->message(_("TeX mode"));
1404                 return true;    
1405         }
1406
1407         // no special circumstances, so insert the character without any fuss
1408         insert(c, lastcode_);
1409         lastcode_ = LM_TC_MIN;
1410         return true;
1411 }
1412
1413
1414
1415 MathCursorPos MathCursor::normalAnchor() const
1416 {
1417         lyx::Assert(Anchor_.size() >= Cursor_.size());
1418         // use Anchor on the same level as Cursor
1419         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1420         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1421                 // anchor is behind cursor -> move anchor behind the inset
1422                 ++normal.pos_;
1423         }
1424         return normal;
1425 }
1426
1427
1428 void MathCursor::stripFromLastEqualSign()
1429 {
1430         // find position of last '=' in the array
1431         MathArray & ar = cursor().cell();
1432         MathArray::const_iterator et = ar.end();
1433         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
1434                 if ((*it)->getChar() == '=')
1435                         et = it;
1436
1437         // delete everything behind this position
1438         ar.erase(et - ar.begin(), ar.size());
1439         pos() = ar.size(); 
1440 }
1441
1442