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