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