]> git.lyx.org Git - features.git/blob - src/mathed/math_cursor.C
- remove some unused code
[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                 // correct cursor position
1071                 --idx();
1072                 pos() = size();
1073         }
1074 }
1075
1076
1077 char MathCursor::valign() const
1078 {
1079         idx_type idx;
1080         MathArrayInset * p = enclosingArray(idx);
1081         return p ? p->valign() : '\0';
1082 }
1083
1084
1085 char MathCursor::halign() const
1086 {
1087         idx_type idx;
1088         MathArrayInset * p = enclosingArray(idx);
1089         return p ? p->halign(idx % p->ncols()) : '\0';
1090 }
1091
1092
1093 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1094 {
1095         MathCursorPos anc = normalAnchor();
1096         if (anc < cursor()) {
1097                 i1 = anc;
1098                 i2 = cursor();
1099         } else {
1100                 i1 = cursor();
1101                 i2 = anc;
1102         }
1103 }
1104
1105
1106 MathCursorPos & MathCursor::cursor()
1107 {
1108         return Cursor_.back();
1109 }
1110
1111
1112 MathCursorPos const & MathCursor::cursor() const
1113 {
1114         return Cursor_.back();
1115 }
1116
1117
1118 int MathCursor::cellXOffset() const
1119 {
1120         return par()->cellXOffset(idx());
1121 }
1122
1123
1124 int MathCursor::cellYOffset() const
1125 {
1126         return par()->cellYOffset(idx());
1127 }
1128
1129
1130 int MathCursor::xpos() const
1131 {
1132         return cellXOffset() + xarray().pos2x(pos());
1133 }
1134
1135
1136 int MathCursor::ypos() const
1137 {
1138         return cellYOffset();
1139 }
1140
1141
1142
1143 void MathCursor::gotoX(int x) 
1144 {
1145         pos() = xarray().x2pos(x - cellXOffset());
1146 }
1147
1148
1149 bool MathCursor::goUp()
1150 {
1151         // first ask the inset if it knows better then we
1152         if (par()->idxUp(idx(), pos()))
1153                 return true;
1154
1155         // leave subscript to the nearest side  
1156         MathScriptInset * p = par()->asScriptInset();
1157         if (p && idx() == 0) {
1158                 if (pos() <= size() / 2)
1159                         popLeft();
1160                 else
1161                         popRight();             
1162                 return true;
1163         }
1164
1165         // if not, apply brute force.
1166         int x0;
1167         int y0;
1168         getPos(x0, y0);
1169         std::vector<MathCursorPos> save = Cursor_;
1170         MathAtom const & out = formula()->par();
1171         y0 -= xarray().ascent();
1172         for (int y = y0 - 4; y > out->yo() - out->ascent(); y -= 4) {
1173                 setPos(x0, y);
1174                 if (save != Cursor_ && xarray().yo() < y0)
1175                         return true;    
1176         }
1177         Cursor_ = save;
1178         return false;
1179 }
1180
1181
1182 bool MathCursor::goDown()
1183 {
1184         // first ask the inset if it knows better then we
1185         if (par()->idxDown(idx(), pos()))
1186                 return true;
1187
1188         // leave superscript to the nearest side        
1189         MathScriptInset * p = par()->asScriptInset();
1190         if (p && idx() == 1) {
1191                 if (pos() <= size() / 2)
1192                         popLeft();
1193                 else
1194                         popRight();             
1195                 return true;
1196         }
1197
1198         // if not, apply brute force.
1199         int x0;
1200         int y0;
1201         getPos(x0, y0);
1202         std::vector<MathCursorPos> save = Cursor_;
1203         MathAtom const & out = formula()->par();
1204         y0 += xarray().descent();
1205         for (int y = y0 + 4; y < out->yo() + out->descent(); y += 4) {
1206                 setPos(x0, y);
1207                 if (save != Cursor_ && xarray().yo() > y0)
1208                         return true;    
1209         }
1210         Cursor_ = save;
1211         return false;
1212 }
1213
1214
1215 bool MathCursor::idxLeft()
1216 {
1217         return par()->idxLeft(idx(), pos());
1218 }
1219
1220
1221 bool MathCursor::idxRight()
1222 {
1223         return par()->idxRight(idx(), pos());
1224 }
1225
1226
1227 void MathCursor::interpret(string const & s)
1228 {
1229         //lyxerr << "interpret 1: '" << s << "'\n";
1230         if (s.empty())
1231                 return;
1232
1233         if (s.size() == 1) {
1234                 interpret(s[0]);
1235                 return;
1236         }
1237
1238         //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
1239         //owner_->getIntl()->getTrans().TranslateAndInsert(s[0], lt);   
1240         //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
1241
1242         if (s.size() > 7 && s.substr(0, 7) == "matrix ") {
1243                 unsigned int m = 1;
1244                 unsigned int n = 1;
1245                 string v_align;
1246                 string h_align;
1247                 istringstream is(s.substr(7).c_str());
1248                 is >> m >> n >> v_align >> h_align;
1249                 m = std::max(1u, m);
1250                 n = std::max(1u, n);
1251                 v_align += 'c';
1252                 niceInsert(MathAtom(new MathArrayInset(m, n, v_align[0], h_align)));
1253                 return;
1254         }
1255
1256         if (s == "\\over" || s == "\\choose" || s == "\\atop") {
1257                 MathArray ar = array();
1258                 MathAtom t = createMathInset(s.substr(1));
1259                 t->asNestInset()->cell(0).swap(array());
1260                 pos() = 0;
1261                 niceInsert(t);
1262                 popRight();
1263                 left();
1264                 return;
1265         }
1266
1267         niceInsert(createMathInset(s.substr(1)));
1268 }
1269
1270
1271 void MathCursor::interpret(char c)
1272 {
1273         //lyxerr << "interpret 2: '" << c << "'\n";
1274
1275         if (inMacroMode()) {
1276                 string name = macroName();
1277
1278                 if (name == "\\" && c == '#') {
1279                         insert(c, LM_TC_TEX);
1280                         return;
1281                 }
1282
1283                 if (name == "\\" && c == '\\') {
1284                         backspace();
1285                         interpret("\\backslash");
1286                         return;
1287                 }
1288
1289                 if (name == "\\#" && '1' <= c && c <= '9') {
1290                         insert(c, LM_TC_TEX);
1291                         macroModeClose();
1292                         return;
1293                 }
1294
1295                 if (isalpha(c)) {
1296                         insert(c, LM_TC_TEX);
1297                         return;
1298                 }
1299
1300                 if (name == "\\") {
1301                         insert(c, LM_TC_TEX);
1302                         macroModeClose();
1303                         return;
1304                 }
1305
1306                 macroModeClose();
1307                 return;
1308         }
1309
1310         // no macro mode
1311         if (c == '^' || c == '_') {
1312                 const bool up = (c == '^');
1313                 selCut();
1314                 if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1315                         prevAtom()->asScriptInset()->ensure(up);
1316                         pushRight(prevAtom());
1317                         idx() = up;
1318                         pos() = size();
1319                 } else if (hasNextAtom() && nextAtom()->asScriptInset()) {
1320                         nextAtom()->asScriptInset()->ensure(up);
1321                         pushLeft(nextAtom());
1322                         idx() = up;
1323                         pos() = 0;
1324                 } else {
1325                         plainInsert(MathAtom(new MathScriptInset(up)));
1326                         prevAtom()->asScriptInset()->ensure(up);
1327                         pushRight(prevAtom());
1328                         idx() = up;
1329                         pos() = 0;
1330                 }
1331                 selPaste();
1332                 dump("1");
1333                 return;
1334         }
1335
1336         if (selection_)
1337                 selDel();
1338
1339         if (lastcode_ == LM_TC_TEXTRM) {
1340                 insert(c, LM_TC_TEXTRM);
1341                 return;
1342         }
1343
1344         if (c == ' ') {
1345                 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1346                         prevAtom()->asSpaceInset()->incSpace();
1347                         return;
1348                 }
1349
1350                 if (mathcursor->popRight())
1351                         return;
1352
1353 #warning look here
1354                         // this would not work if the inset is in an table!
1355                         //bv->text->cursorRight(bv, true);
1356                         //result = FINISHED;
1357                 return;
1358         }
1359
1360         if (strchr("{}", c)) {
1361                 insert(c, LM_TC_TEX);
1362                 return;
1363         }
1364
1365         if (strchr("#$%", c)) {
1366                 insert(MathAtom(new MathSpecialCharInset(c)));  
1367                 lastcode_ = LM_TC_VAR;
1368                 return;
1369         }
1370
1371         if (isalpha(c) && lastcode_ == LM_TC_GREEK) {
1372                 insert(c, LM_TC_VAR);
1373                 return; 
1374         }
1375
1376         if (isalpha(c) && lastcode_ == LM_TC_GREEK1) {
1377                 insert(c, LM_TC_VAR);
1378                 lastcode_ = LM_TC_VAR;
1379                 return; 
1380         }
1381
1382         if (c == '\\') {
1383                 insert(c, LM_TC_TEX);
1384                 //bv->owner()->message(_("TeX mode"));
1385                 return; 
1386         }
1387
1388         // no special circumstances, so insert the character without any fuss
1389         insert(c, LM_TC_MIN);
1390 }
1391
1392
1393
1394 ////////////////////////////////////////////////////////////////////////
1395
1396
1397 bool operator==(MathCursorPos const & ti, MathCursorPos const & it)
1398 {
1399         return ti.par_ == it.par_ && ti.idx_ == it.idx_ && ti.pos_ == it.pos_;
1400 }
1401
1402
1403 bool operator<(MathCursorPos const & ti, MathCursorPos const & it)
1404 {
1405         if (ti.par_ != it.par_) {
1406                 lyxerr << "can't compare cursor and anchor in different insets\n";
1407                 return true;
1408         }
1409         if (ti.idx_ != it.idx_)
1410                 return ti.idx_ < it.idx_;
1411         return ti.pos_ < it.pos_;
1412 }
1413
1414
1415 MathArray & MathCursorPos::cell(MathCursor::idx_type idx) const
1416 {
1417         return (*par_)->cell(idx);
1418 }
1419
1420
1421 MathArray & MathCursorPos::cell() const
1422 {
1423         return (*par_)->cell(idx_);
1424 }
1425
1426
1427 MathXArray & MathCursorPos::xcell(MathCursor::idx_type idx) const
1428 {
1429         return (*par_)->xcell(idx);
1430 }
1431
1432
1433 MathXArray & MathCursorPos::xcell() const
1434 {
1435         return (*par_)->xcell(idx_);
1436 }
1437
1438
1439 MathCursorPos MathCursor::normalAnchor() const
1440 {
1441         // use Anchor on the same level as Cursor
1442         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1443         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1444                 // anchor is behind cursor -> move anchor behind the inset
1445                 ++normal.pos_;
1446         }
1447         return normal;
1448 }
1449
1450