]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
fix for #219
[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(MathAtom const & t)
446 {
447         macroModeClose();
448
449         if (selection_) {
450                 if (t->nargs())
451                         selCut();
452                 else
453                         selDel();
454         }
455
456         plainInsert(t);
457 }
458
459
460 void MathCursor::niceInsert(MathAtom const & t)
461 {
462         selCut();
463         insert(t); // inserting invalidates the pointer!
464         MathAtom const & p = prevAtom();
465         if (p->nargs()) {
466                 posLeft();
467                 right();  // do not push for e.g. MathSymbolInset
468                 selPaste();
469         }
470 }
471
472
473 void MathCursor::insert(MathArray const & ar)
474 {
475         macroModeClose();
476         if (selection_)
477                 selCut();
478
479         array().insert(pos(), ar);
480         pos() += ar.size();
481 }
482
483
484 void MathCursor::paste(MathArray const & ar)
485 {
486         Anchor_ = Cursor_;
487         selection_ = true;
488         array().insert(pos(), ar);
489         pos() += ar.size();
490 }
491
492
493 void MathCursor::backspace()
494 {
495         if (pos() == 0) {
496                 pullArg(false);
497                 return;
498         }
499
500         if (selection_) {
501                 selDel();
502                 return;
503         }
504
505         MathScriptInset * p = prevAtom()->asScriptInset();
506         if (p) {
507                 p->removeScript(p->hasUp());
508                 // Don't delete if there is anything left
509                 if (p->hasUp() || p->hasDown())
510                         return;
511         }
512
513         --pos();
514         plainErase();
515 }
516
517
518 void MathCursor::erase()
519 {
520         if (inMacroMode())
521                 return;
522
523         if (selection_) {
524                 selDel();
525                 return;
526         }
527
528         // delete empty cells if necessary
529         if (array().empty()) {
530                 bool popit;
531                 bool removeit;
532                 par()->idxDelete(idx(), popit, removeit);
533                 if (popit && popLeft() && removeit)
534                         plainErase();
535                 return;
536         }
537
538         if (pos() == size())
539                 return;
540
541         MathScriptInset * p = nextAtom()->asScriptInset();
542         if (p) {
543                 p->removeScript(p->hasUp());
544                 // Don't delete if there is anything left
545                 if (p->hasUp() || p->hasDown())
546                         return;
547         }
548
549         plainErase();
550 }
551
552
553 void MathCursor::delLine()
554 {
555         macroModeClose();
556
557         if (selection_) {
558                 selDel();
559                 return;
560         }
561
562         if (par()->nrows() > 1) {
563                 // grid are the only things with more than one row...
564                 lyx::Assert(par()->asGridInset());
565                 par()->asGridInset()->delRow(hullRow());
566         }
567
568         if (idx() > par()->nargs())
569                 idx() = par()->nargs();
570
571         if (pos() > size())
572                 pos() = size();
573 }
574
575
576 bool MathCursor::up(bool sel)
577 {
578         dump("up 1");
579         macroModeClose();
580         selHandle(sel);
581         cursor_type save = Cursor_;
582         if (goUpDown(true))
583                 return true;
584         Cursor_ = save;
585         return selection_;
586 }
587
588
589 bool MathCursor::down(bool sel)
590 {
591         dump("down 1");
592         macroModeClose();
593         selHandle(sel);
594         cursor_type save = Cursor_;
595         if (goUpDown(false))
596                 return true;
597         Cursor_ = save;
598         return selection_;
599 }
600
601
602 bool MathCursor::toggleLimits()
603 {
604         if (!hasNextAtom())
605                 return false;
606         MathScriptInset * t = nextAtom()->asScriptInset();
607         if (!t)
608                 return false;
609         int old = t->limits();
610         t->limits(old < 0 ? 1 : -1);
611         return old != t->limits();
612 }
613
614
615 void MathCursor::macroModeClose()
616 {
617         string s = macroName();
618         if (s.size()) {
619                 size_type old = pos();
620                 pos() -= s.size();
621                 array().erase(pos(), old);
622                 interpret(s);
623         }
624 }
625
626
627 MathInset::difference_type MathCursor::macroNamePos() const
628 {
629         for (MathInset::difference_type i = pos() - 1; i >= 0; --i) {
630                 MathAtom & p = array().at(i);
631                 if (p->code() == LM_TC_TEX && p->getChar() == '\\')
632                         return i;
633         }
634         return -1;
635 }
636
637
638 string MathCursor::macroName() const
639 {
640         string s;
641         MathInset::difference_type i = macroNamePos();
642         for ( ; i >= 0 && i < int(pos()); ++i)
643                 s += array().at(i)->getChar();
644         return s;
645 }
646
647
648 void MathCursor::selCopy()
649 {
650         dump("selCopy");
651         if (selection_) {
652                 theSelection.grab(*this);
653                 selClear();
654         }
655 }
656
657
658 void MathCursor::selCut()
659 {
660         dump("selCut");
661         if (selection_) {
662                 theSelection.grab(*this);
663                 theSelection.erase(*this);
664                 selClear();
665         } else {
666                 theSelection.clear();
667         }
668 }
669
670
671 void MathCursor::selDel()
672 {
673         dump("selDel");
674         if (selection_) {
675                 theSelection.erase(*this);
676                 if (pos() > size())
677                         pos() = size();
678                 selClear();
679         }
680 }
681
682
683 void MathCursor::selPaste()
684 {
685         dump("selPaste");
686         theSelection.paste(*this);
687         //theSelection.grab(*this);
688         //selClear();
689 }
690
691
692 void MathCursor::selHandle(bool sel)
693 {
694         if (sel == selection_)
695                 return;
696         //theSelection.clear();
697         Anchor_    = Cursor_;
698         selection_ = sel;
699 }
700
701
702 void MathCursor::selStart()
703 {
704         dump("selStart 1");
705         //theSelection.clear();
706         Anchor_ = Cursor_;
707         selection_ = true;
708         dump("selStart 2");
709 }
710
711
712 void MathCursor::selClear()
713 {
714         dump("selClear 1");
715         selection_ = false;
716         dump("selClear 2");
717 }
718
719
720 void MathCursor::selGet(MathArray & ar)
721 {
722         dump("selGet");
723         if (!selection_)
724                 return;
725
726         theSelection.grab(*this);
727         ar = theSelection.glue();
728 }
729
730
731
732 void MathCursor::drawSelection(Painter & pain) const
733 {
734         if (!selection_)
735                 return;
736
737         MathCursorPos i1;
738         MathCursorPos i2;
739         getSelection(i1, i2);
740
741         if (i1.idx_ == i2.idx_) {
742                 MathXArray & c = i1.xcell();
743                 int x1 = c.xo() + c.pos2x(i1.pos_);
744                 int y1 = c.yo() - c.ascent();
745                 int x2 = c.xo() + c.pos2x(i2.pos_);
746                 int y2 = c.yo() + c.descent();
747                 pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
748         } else {
749                 std::vector<MathInset::idx_type> indices
750                         = i1.par_->idxBetween(i1.idx_, i2.idx_);
751                 for (unsigned i = 0; i < indices.size(); ++i) {
752                         MathXArray & c = i1.xcell(indices[i]);
753                         int x1 = c.xo();
754                         int y1 = c.yo() - c.ascent();
755                         int x2 = c.xo() + c.width();
756                         int y2 = c.yo() + c.descent();
757                         pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
758                 }
759         }
760
761 #if 0
762         // draw anchor if different from selection boundary
763         MathCursorPos anc = Anchor_.back();
764         if (anc != i1 && anc != i2) {
765                 MathXArray & c = anc.xcell();
766                 int x  = c.xo() + c.pos2x(anc.pos_);
767                 int y1 = c.yo() - c.ascent();
768                 int y2 = c.yo() + c.descent();
769                 pain.line(x, y1, x, y2, LColor::math);
770         }
771 #endif
772 }
773
774
775 void MathCursor::handleFont(MathTextCodes t)
776 {
777         macroModeClose();
778         if (selection_) {
779                 MathCursorPos i1;
780                 MathCursorPos i2;
781                 getSelection(i1, i2);
782                 if (i1.idx_ == i2.idx_) {
783                         MathArray & ar = i1.cell();
784                         for (MathInset::pos_type pos = i1.pos_; pos != i2.pos_; ++pos)
785                                 ar.at(pos)->handleFont(t);
786                 }
787         } else
788                 lastcode_ = (lastcode_ == t) ? LM_TC_VAR : t;
789 }
790
791
792 void MathCursor::handleDelim(string const & l, string const & r)
793 {
794         handleNest(new MathDelimInset(l, r));
795 }
796
797
798 void MathCursor::handleNest(MathInset * p)
799 {
800         if (selection_) {
801                 selCut();
802                 p->cell(0) = theSelection.glue();
803         }
804         insert(MathAtom(p)); // this invalidates p!
805         pushRight(prevAtom());
806 }
807
808
809 void MathCursor::getPos(int & x, int & y)
810 {
811 #ifdef WITH_WARNINGS
812 #warning This should probably take cellXOffset and cellYOffset into account
813 #endif
814         x = xarray().xo() + xarray().pos2x(pos());
815         y = xarray().yo();
816 }
817
818
819 MathInset * MathCursor::par() const
820 {
821         return cursor().par_;
822 }
823
824
825 InsetFormulaBase * MathCursor::formula()
826 {
827         return formula_;
828 }
829
830
831 MathCursor::idx_type MathCursor::idx() const
832 {
833         return cursor().idx_;
834 }
835
836
837 MathCursor::idx_type & MathCursor::idx()
838 {
839         return cursor().idx_;
840 }
841
842
843 MathCursor::pos_type MathCursor::pos() const
844 {
845         return cursor().pos_;
846 }
847
848
849 MathCursor::pos_type & MathCursor::pos()
850 {
851         return cursor().pos_;
852 }
853
854
855 bool MathCursor::inMacroMode() const
856 {
857         return macroNamePos() != -1;
858 }
859
860
861 bool MathCursor::inMacroArgMode() const
862 {
863         return pos() > 0 && prevAtom()->getChar() == '#';
864 }
865
866
867 bool MathCursor::selection() const
868 {
869         return selection_;
870 }
871
872
873 MathGridInset * MathCursor::enclosingGrid(MathCursor::idx_type & idx) const
874 {
875         for (MathInset::difference_type i = Cursor_.size() - 1; i >= 0; --i) {
876                 MathGridInset * p = Cursor_[i].par_->asGridInset();
877                 if (p) {
878                         idx = Cursor_[i].idx_;
879                         return p;
880                 }
881         }
882         return 0;
883 }
884
885
886 void MathCursor::pullArg(bool goright)
887 {
888         dump("pullarg");
889         MathArray a = array();
890
891         MathScriptInset const * p = par()->asScriptInset();
892         if (p) {
893                 // special handling for scripts
894                 const bool up = p->hasUp();
895                 popLeft();
896                 MathScriptInset * q = nextAtom()->asScriptInset();
897                 if (q)
898                         q->removeScript(up);
899                 ++pos();
900                 array().insert(pos(), a);
901                 return;
902         }
903
904         if (popLeft()) {
905                 plainErase();
906                 array().insert(pos(), a);
907                 if (goright)
908                         pos() += a.size();
909         }
910 }
911
912
913 void MathCursor::normalize()
914 {
915         // rebreak
916         {
917                 MathIterator it = ibegin(formula()->par().nucleus());
918                 MathIterator et = iend(formula()->par().nucleus());
919                 for ( ; it != et; ++it)
920                         if (it.par()->asBoxInset())
921                                 it.par()->asBoxInset()->rebreak();
922         }
923
924         if (idx() >= par()->nargs()) {
925                 lyxerr << "this should not really happen - 1: "
926                        << idx() << " " << par()->nargs() << "\n";
927                 dump("error 2");
928         }
929         idx() = min(idx(), par()->nargs() - 1);
930
931         if (pos() > size()) {
932                 lyxerr << "this should not really happen - 2: "
933                         << pos() << " " << size() <<  " in idx: " << idx()
934                         << " in atom: '";
935                 WriteStream wi(lyxerr, false);
936                 par()->write(wi);
937                 lyxerr << "\n";
938                 dump("error 4");
939         }
940         pos() = min(pos(), size());
941 }
942
943
944 MathCursor::size_type MathCursor::size() const
945 {
946         return array().size();
947 }
948
949
950 MathCursor::col_type MathCursor::hullCol() const
951 {
952         return Cursor_[0].par_->asGridInset()->col(Cursor_[0].idx_);
953 }
954
955
956 MathCursor::row_type MathCursor::hullRow() const
957 {
958         return Cursor_[0].par_->asGridInset()->row(Cursor_[0].idx_);
959 }
960
961
962 bool MathCursor::hasPrevAtom() const
963 {
964         return pos() > 0;
965 }
966
967
968 bool MathCursor::hasNextAtom() const
969 {
970         return pos() < size();
971 }
972
973
974 MathAtom const & MathCursor::prevAtom() const
975 {
976         lyx::Assert(pos() > 0);
977         return array().at(pos() - 1);
978 }
979
980
981 MathAtom & MathCursor::prevAtom()
982 {
983         lyx::Assert(pos() > 0);
984         return array().at(pos() - 1);
985 }
986
987
988 MathAtom const & MathCursor::nextAtom() const
989 {
990         lyx::Assert(pos() < size());
991         return array().at(pos());
992 }
993
994
995 MathAtom & MathCursor::nextAtom()
996 {
997         lyx::Assert(pos() < size());
998         return array().at(pos());
999 }
1000
1001
1002 MathArray & MathCursor::array() const
1003 {
1004         static MathArray dummy;
1005
1006         if (idx() >= par()->nargs()) {
1007                 lyxerr << "############  idx_ " << idx() << " not valid\n";
1008                 return dummy;
1009         }
1010
1011         if (Cursor_.size() == 0) {
1012                 lyxerr << "############  Cursor_.size() == 0 not valid\n";
1013                 return dummy;
1014         }
1015
1016         return cursor().cell();
1017 }
1018
1019
1020 MathXArray & MathCursor::xarray() const
1021 {
1022         static MathXArray dummy;
1023
1024         if (Cursor_.size() == 0) {
1025                 lyxerr << "############  Cursor_.size() == 0 not valid\n";
1026                 return dummy;
1027         }
1028
1029         return cursor().xcell();
1030 }
1031
1032
1033 void MathCursor::idxNext()
1034 {
1035         par()->idxNext(idx(), pos());
1036 }
1037
1038
1039 void MathCursor::idxPrev()
1040 {
1041         par()->idxPrev(idx(), pos());
1042 }
1043
1044
1045 void MathCursor::splitCell()
1046 {
1047         if (idx() + 1 == par()->nargs())
1048                 return;
1049         MathArray ar = array();
1050         ar.erase(0, pos());
1051         array().erase(pos(), size());
1052         ++idx();
1053         pos() = 0;
1054         array().insert(0, ar);
1055 }
1056
1057
1058 void MathCursor::breakLine()
1059 {
1060         // leave inner cells
1061         while (popRight())
1062                 ;
1063
1064         MathHullInset * p = formula()->par()->asHullInset();
1065         if (!p)
1066                 return;
1067
1068         if (p->getType() == LM_OT_SIMPLE || p->getType() == LM_OT_EQUATION) {
1069                 p->mutate(LM_OT_EQNARRAY);
1070                 idx() = 0;
1071                 pos() = size();
1072         } else {
1073                 p->addRow(hullRow());
1074
1075                 // split line
1076                 const row_type r = hullRow();
1077                 for (col_type c = hullCol() + 1; c < p->ncols(); ++c)
1078                         p->cell(p->index(r, c)).swap(p->cell(p->index(r + 1, c)));
1079
1080                 // split cell
1081                 splitCell();
1082                 p->cell(idx()).swap(p->cell(idx() + p->ncols() - 1));
1083         }
1084 }
1085
1086
1087 //void MathCursor::readLine(MathArray & ar) const
1088 //{
1089 //      idx_type base = row() * par()->ncols();
1090 //      for (idx_type off = 0; off < par()->ncols(); ++off)
1091 //              ar.push_back(par()->cell(base + off));
1092 //}
1093
1094
1095 char MathCursor::valign() const
1096 {
1097         idx_type idx;
1098         MathGridInset * p = enclosingGrid(idx);
1099         return p ? p->valign() : '\0';
1100 }
1101
1102
1103 char MathCursor::halign() const
1104 {
1105         idx_type idx;
1106         MathGridInset * p = enclosingGrid(idx);
1107         return p ? p->halign(idx % p->ncols()) : '\0';
1108 }
1109
1110
1111 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1112 {
1113         MathCursorPos anc = normalAnchor();
1114         if (anc < cursor()) {
1115                 i1 = anc;
1116                 i2 = cursor();
1117         } else {
1118                 i1 = cursor();
1119                 i2 = anc;
1120         }
1121 }
1122
1123
1124 MathCursorPos & MathCursor::cursor()
1125 {
1126         lyx::Assert(Cursor_.size());
1127         return Cursor_.back();
1128 }
1129
1130
1131 MathCursorPos const & MathCursor::cursor() const
1132 {
1133         lyx::Assert(Cursor_.size());
1134         return Cursor_.back();
1135 }
1136
1137
1138 bool MathCursor::goUpDown(bool up)
1139 {
1140         int xlow, xhigh, ylow, yhigh;
1141
1142   int xo, yo;
1143         getPos(xo, yo);
1144
1145         // try current cell first
1146         xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1147         if (up)
1148                 yhigh = yo - 4;
1149         else
1150                 ylow = yo + 4;
1151         if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh))
1152                 return true;
1153
1154         // try to find an inset that knows better then we
1155         while (1) {
1156                 // we found a cell that think something "below" us.
1157                 if (up) {
1158                         if (par()->idxUp(idx()))
1159                                 break;
1160                 } else {
1161                         if (par()->idxDown(idx()))
1162                                 break;
1163                 }
1164
1165                 if (!popLeft()) {
1166                         // no such inset found, just take something "above"
1167                         return
1168                                 bruteFind(xo, yo,
1169                                         formula()->xlow(),
1170                                         formula()->xhigh(),
1171                                         up ? formula()->ylow() : yo + 4,
1172                                         up ? yo - 4 : formula()->yhigh()
1173                                 );
1174                 }
1175         }
1176         xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1177         bruteFind(xo, yo, xlow, xhigh, ylow, yhigh);
1178         return true;
1179 }
1180
1181
1182 bool MathCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1183 {
1184         cursor_type best_cursor;
1185         double best_dist = 1e10;
1186
1187         MathIterator it = ibegin(formula()->par().nucleus());
1188         MathIterator et = iend(formula()->par().nucleus());
1189         while (1) {
1190                 // avoid invalid nesting hen selecting
1191                 if (selection_ && !positionable(it.cursor(), Anchor_))
1192                         continue;
1193                 int xo = it.position().xpos();
1194                 int yo = it.position().ypos();
1195                 if (xlow - 2 <= xo && xo <= xhigh + 2 &&
1196                     ylow - 2 <= yo && yo <= yhigh + 2)
1197                 {
1198                         double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1199                         if (d < best_dist) {
1200                                 best_dist   = d;
1201                                 best_cursor = it.cursor();
1202                         }
1203                 }
1204
1205                 if (it == et)
1206                         break;
1207                 ++it;
1208         }
1209
1210         if (best_dist < 1e10)
1211                 Cursor_ = best_cursor;
1212         return best_dist < 1e10;
1213 }
1214
1215
1216 bool MathCursor::idxLeft()
1217 {
1218         return par()->idxLeft(idx(), pos());
1219 }
1220
1221
1222 bool MathCursor::idxRight()
1223 {
1224         return par()->idxRight(idx(), pos());
1225 }
1226
1227
1228 bool MathCursor::interpret(string const & s)
1229 {
1230         //lyxerr << "interpret 1: '" << s << "'\n";
1231         if (s.empty())
1232                 return true;
1233
1234         if (s.size() == 1)
1235                 return interpret(s[0]);
1236
1237         //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
1238         //owner_->getIntl()->getTrans().TranslateAndInsert(s[0], lt);
1239         //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
1240
1241         if (s.size() >= 5 && s.substr(0, 5) == "cases") {
1242                 unsigned int n = 1;
1243                 istringstream is(s.substr(5).c_str());
1244                 is >> n;
1245                 n = std::max(1u, n);
1246                 niceInsert(MathAtom(new MathCasesInset(n)));
1247                 return true;
1248         }
1249
1250         if (s.size() >= 6 && s.substr(0, 6) == "matrix") {
1251                 unsigned int m = 1;
1252                 unsigned int n = 1;
1253                 string v_align;
1254                 string h_align;
1255                 istringstream is(s.substr(6).c_str());
1256                 is >> m >> n >> v_align >> h_align;
1257                 m = std::max(1u, m);
1258                 n = std::max(1u, n);
1259                 v_align += 'c';
1260                 niceInsert(MathAtom(new MathArrayInset(m, n, v_align[0], h_align)));
1261                 return true;
1262         }
1263
1264         if (s.size() >= 7 && s.substr(0, 7) == "replace") {
1265                 ReplaceData rep;
1266                 istringstream is(s.substr(7).c_str());
1267                 string from, to;
1268                 is >> from >> to;
1269                 mathed_parse_cell(rep.from, from);
1270                 mathed_parse_cell(rep.to, to);
1271                 lyxerr << "replacing '" << from << "' with '" << to << "'\n";
1272                 par()->replace(rep);
1273                 return true;
1274         }
1275
1276         if (s == "\\over" || s == "\\choose" || s == "\\atop") {
1277                 MathArray ar = array();
1278                 MathAtom t(createMathInset(s.substr(1)));
1279                 t->asNestInset()->cell(0).swap(array());
1280                 pos() = 0;
1281                 niceInsert(t);
1282                 popRight();
1283                 left();
1284                 return true;
1285         }
1286
1287         latexkeys const * l = in_word_set(s.substr(1));
1288         if (l && (l->token == LM_TK_FONT || l->token == LM_TK_OLDFONT)) {
1289                 lastcode_ = static_cast<MathTextCodes>(l->id);
1290                 return true;
1291         }
1292
1293         niceInsert(createMathInset(s.substr(1)));
1294         return true;
1295 }
1296
1297
1298 bool MathCursor::script(bool up)
1299 {
1300         macroModeClose();
1301         selCut();
1302         if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1303                 prevAtom()->asScriptInset()->ensure(up);
1304                 pushRight(prevAtom());
1305                 idx() = up;
1306                 pos() = size();
1307         } else if (hasNextAtom() && nextAtom()->asScriptInset()) {
1308                 nextAtom()->asScriptInset()->ensure(up);
1309                 pushLeft(nextAtom());
1310                 idx() = up;
1311                 pos() = 0;
1312         } else {
1313                 plainInsert(MathAtom(new MathScriptInset(up)));
1314                 prevAtom()->asScriptInset()->ensure(up);
1315                 pushRight(prevAtom());
1316                 idx() = up;
1317                 pos() = 0;
1318         }
1319         selPaste();
1320         dump("1");
1321         return true;
1322 }
1323
1324
1325 bool MathCursor::interpret(char c)
1326 {
1327         if (inMacroArgMode()) {
1328                 --pos();
1329                 plainErase();
1330                 if ('1' <= c && c <= '9')
1331                         insert(MathAtom(new MathMacroArgument(c - '0')));
1332                 else {
1333                         insert(MathAtom(new MathSpecialCharInset('#')));
1334                         interpret(c); // try again
1335                 }
1336                 return true;
1337         }
1338
1339         // handle macroMode
1340         if (inMacroMode()) {
1341                 string name = macroName();
1342
1343                 if (name == "\\" && c == '\\') {
1344                         backspace();
1345                         interpret("\\backslash");
1346                         return true;
1347                 }
1348
1349                 if (isalpha(c)) {
1350                         insert(c, LM_TC_TEX);
1351                         return true;
1352                 }
1353
1354                 if (name == "\\") {
1355                         insert(c, LM_TC_TEX);
1356                         macroModeClose();
1357                         return true;
1358                 }
1359
1360                 macroModeClose();
1361
1362                 if (c == '\\')
1363                         insert(c, LM_TC_TEX);
1364
1365                 return true;
1366         }
1367
1368         if (selection_) {
1369                 selClear();
1370                 if (c == ' ')
1371                         return true;
1372                 // fall through in the other cases
1373         }
1374
1375         if (lastcode_ == LM_TC_TEXTRM || par()->asBoxInset()) {
1376                 // suppress direct insertion of two spaces in a row
1377                 // the still allows typing  '<space>a<space>' and deleting the 'a', but
1378                 // it is better than nothing...
1379                 if (c == ' ' && hasPrevAtom() && prevAtom()->getChar() == ' ')
1380                         return true;
1381                 insert(c, LM_TC_TEXTRM);
1382                 return true;
1383         }
1384
1385         if (c == ' ') {
1386                 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1387                         prevAtom()->asSpaceInset()->incSpace();
1388                         return true;
1389                 }
1390                 if (popRight())
1391                         return true;
1392                 // if are at the very end, leave the formula
1393                 return pos() != size();
1394         }
1395
1396         if (c == '#') {
1397                 insert(c, LM_TC_TEX);
1398                 return true;
1399         }
1400
1401 /*
1402         if (strchr("{}", c)) {
1403                 insert(c, LM_TC_TEX);
1404                 return true;
1405         }
1406 */
1407
1408         if (c == '{') {
1409                 niceInsert(MathAtom(new MathBraceInset));
1410                 return true;
1411         }
1412
1413         if (c == '}') {
1414                 return true;
1415         }
1416
1417         if (strchr("$%", c)) {
1418                 insert(MathAtom(new MathSpecialCharInset(c)));
1419                 lastcode_ = LM_TC_VAR;
1420                 return true;
1421         }
1422
1423         if (isalpha(c) && lastcode_ == LM_TC_GREEK) {
1424                 insert(c, LM_TC_VAR);
1425                 return true;
1426         }
1427
1428         if (isalpha(c) && lastcode_ == LM_TC_GREEK1) {
1429                 insert(c, LM_TC_VAR);
1430                 lastcode_ = LM_TC_VAR;
1431                 return true;
1432         }
1433
1434         if (c == '\\') {
1435                 insert(c, LM_TC_TEX);
1436                 //bv->owner()->message(_("TeX mode"));
1437                 return true;
1438         }
1439
1440         // no special circumstances, so insert the character without any fuss
1441         insert(c, lastcode_ == LM_TC_MIN ? MathCharInset::nativeCode(c) : lastcode_);
1442         lastcode_ = LM_TC_MIN;
1443         return true;
1444 }
1445
1446
1447
1448 MathCursorPos MathCursor::normalAnchor() const
1449 {
1450         if (Anchor_.size() < Cursor_.size()) {
1451                 Anchor_ = Cursor_;
1452                 lyxerr << "unusual Anchor size\n";
1453                 dump("1");
1454         }
1455         //lyx::Assert(Anchor_.size() >= Cursor_.size());
1456         // use Anchor on the same level as Cursor
1457         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1458         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1459                 // anchor is behind cursor -> move anchor behind the inset
1460                 ++normal.pos_;
1461         }
1462         return normal;
1463 }
1464
1465
1466 void MathCursor::stripFromLastEqualSign()
1467 {
1468         // find position of last '=' in the array
1469         MathArray & ar = cursor().cell();
1470         MathArray::const_iterator et = ar.end();
1471         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
1472                 if ((*it)->getChar() == '=')
1473                         et = it;
1474
1475         // delete everything behind this position
1476         ar.erase(et - ar.begin(), ar.size());
1477         pos() = ar.size();
1478 }
1479
1480
1481 void MathCursor::setSelection(cursor_type const & where, size_type n)
1482 {
1483         selection_ = true;
1484         Anchor_ = where;
1485         Cursor_ = where;
1486         cursor().pos_ += n;
1487 }
1488
1489
1490 string MathCursor::info() const
1491 {
1492         std::ostringstream os;
1493         if (pos() > 0)
1494                 prevAtom()->infoize(os);
1495         return os.str();
1496 }