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