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