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