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