]> git.lyx.org Git - features.git/blob - src/mathed/math_cursor.C
019e9fb1402e32ddbe136a1d73e14d0f1b93aa88
[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         if (pos() > size())
562                 pos() = size();
563 }
564
565
566 bool MathCursor::up(bool sel)
567 {
568         dump("up 1");
569         macroModeClose();
570         selHandle(sel);
571
572         if (!selection_) {
573                 // check whether we could move into a superscript 
574                 if (hasPrevAtom()) {
575                         MathAtom & p = prevAtom();
576                         if (p->asScriptInset() && p->asScriptInset()->hasUp()) {
577                                 pushRight(p);
578                                 idx() = 1;
579                                 pos() = size();
580                                 return true;
581                         }
582                 }
583
584                 if (hasNextAtom()) {
585                         MathAtom & n = nextAtom();
586                         if (n->asScriptInset() && n->asScriptInset()->hasUp()) {
587                                 pushLeft(n);
588                                 idx() = 1;
589                                 pos() = 0;
590                                 return true;
591                         }
592                 }
593         }
594
595         return goUp() || selection_;
596 }
597
598
599 bool MathCursor::down(bool sel)
600 {
601         dump("down 1");
602         macroModeClose();
603         selHandle(sel);
604
605         if (!selection_) {
606                 // check whether we could move into a subscript 
607                 if (hasPrevAtom()) {
608                         MathAtom & p = prevAtom();
609                         if (p->asScriptInset() && p->asScriptInset()->hasDown()) {
610                                 pushRight(p);
611                                 idx() = 0;
612                                 pos() = size();
613                                 return true;
614                         }
615                 }
616
617                 if (hasNextAtom()) {
618                         MathAtom & n = nextAtom();
619                         if (n->asScriptInset() && n->asScriptInset()->hasDown()) {
620                                 pushLeft(n);
621                                 idx() = 0;
622                                 pos() = 0;
623                                 return true;
624                         }
625                 }
626         }
627
628         return goDown() || selection_;
629 }
630
631
632 bool MathCursor::toggleLimits()
633 {
634         if (!hasPrevAtom())
635                 return false;
636         MathScriptInset * t = prevAtom()->asScriptInset();
637         if (!t)
638                 return false;
639         int old = t->limits();
640         t->limits(old < 0 ? 1 : -1);
641         return old != t->limits();
642 }
643
644
645 void MathCursor::macroModeClose()
646 {
647         string s = macroName();
648         if (s.size()) {
649                 size_type old = pos();
650                 pos() -= s.size();
651                 array().erase(pos(), old);
652                 interpret(s);
653         }
654 }
655
656
657 int MathCursor::macroNamePos() const
658 {
659         for (int i = pos() - 1; i >= 0; --i) { 
660                 MathAtom & p = array().at(i);
661                 if (p->code() == LM_TC_TEX && p->getChar() == '\\')
662                         return i;
663         }
664         return -1;
665 }
666
667
668 string MathCursor::macroName() const
669 {
670         string s;
671         for (int i = macroNamePos(); i >= 0 && i < int(pos()); ++i) 
672                 s += array().at(i)->getChar();
673         return s;
674 }
675
676
677 void MathCursor::selCopy()
678 {
679         seldump("selCopy");
680         if (selection_) {
681                 theSelection.grab(*this);
682                 selClear();
683         }
684 }
685
686
687 void MathCursor::selCut()
688 {
689         seldump("selCut");
690         if (selection_) {
691                 theSelection.grab(*this);
692                 theSelection.erase(*this);
693                 selClear();
694         } else {
695                 theSelection.clear();
696         }
697 }
698
699
700 void MathCursor::selDel()
701 {
702         seldump("selDel");
703         if (selection_) {
704                 theSelection.erase(*this);
705                 pos() = 0;
706                 selClear();
707         }
708 }
709
710
711 void MathCursor::selPaste()
712 {
713         seldump("selPaste");
714         theSelection.paste(*this);
715         theSelection.grab(*this);
716         //selClear();
717 }
718
719
720 void MathCursor::selHandle(bool sel)
721 {
722         if (sel == selection_)
723                 return;
724
725         theSelection.clear();
726         Anchor_    = Cursor_;
727         selection_ = sel;
728 }
729
730
731 void MathCursor::selStart()
732 {
733         seldump("selStart");
734         if (selection_)
735                 return;
736
737         theSelection.clear();
738         Anchor_ = Cursor_;
739         selection_ = true;
740 }
741
742
743 void MathCursor::selClear()
744 {
745         seldump("selClear");
746         selection_ = false;
747 }
748
749
750 void MathCursor::selGet(MathArray & ar)
751 {
752         seldump("selGet");
753         if (selection_)
754                 return;
755
756         theSelection.grab(*this);
757         ar = theSelection.glue();
758 }
759
760
761
762 void MathCursor::drawSelection(Painter & pain) const
763 {
764         if (!selection_)
765                 return;
766
767         MathCursorPos i1;
768         MathCursorPos i2;
769         getSelection(i1, i2);
770
771         //lyxerr << "selection from: " << i1 << " to " << i2 << "\n";
772
773         if (i1.idx_ == i2.idx_) {
774                 MathXArray & c = i1.xcell();
775                 int x1 = c.xo() + c.pos2x(i1.pos_);
776                 int y1 = c.yo() - c.ascent();
777                 int x2 = c.xo() + c.pos2x(i2.pos_);
778                 int y2 = c.yo() + c.descent();
779                 pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
780         } else {
781                 std::vector<MathInset::idx_type> indices
782                         = (*i1.par_)->idxBetween(i1.idx_, i2.idx_);
783                 for (unsigned i = 0; i < indices.size(); ++i) {
784                         MathXArray & c = i1.xcell(indices[i]);
785                         int x1 = c.xo();
786                         int y1 = c.yo() - c.ascent();
787                         int x2 = c.xo() + c.width();
788                         int y2 = c.yo() + c.descent();
789                         pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
790                 }
791         }
792 }
793
794
795 void MathCursor::handleFont(MathTextCodes t)
796 {
797         macroModeClose();
798         if (selection_) {
799                 MathCursorPos i1;
800                 MathCursorPos i2;
801                 getSelection(i1, i2); 
802                 if (i1.idx_ == i2.idx_) {
803                         MathArray & ar = i1.cell();
804                         for (MathInset::pos_type pos = i1.pos_; pos != i2.pos_; ++pos)
805                                 ar.at(pos)->handleFont(t);
806                 }
807         } else 
808                 lastcode_ = (lastcode_ == t) ? LM_TC_VAR : t;
809 }
810
811
812 void MathCursor::handleDelim(string const & l, string const & r)
813 {
814         handleNest(new MathDelimInset(l, r));
815 }
816
817
818 void MathCursor::handleNest(MathInset * p)
819 {
820         if (selection_) {
821                 selCut();
822                 p->cell(0) = theSelection.glue();
823         }
824         insert(MathAtom(p)); // this invalidates p!
825         pushRight(prevAtom());
826 }
827
828
829 void MathCursor::getPos(int & x, int & y)
830 {
831 #ifdef WITH_WARNINGS
832 #warning This should probably take cellXOffset and cellYOffset into account
833 #endif
834         x = xarray().xo() + xarray().pos2x(pos());
835         y = xarray().yo();
836 }
837
838
839 MathAtom & MathCursor::par() const
840 {
841         return *cursor().par_;
842 }
843
844
845 InsetFormulaBase const * MathCursor::formula()
846 {
847         return formula_;
848 }
849
850
851 MathCursor::idx_type MathCursor::idx() const
852 {
853         return cursor().idx_;
854 }
855
856
857 MathCursor::idx_type & MathCursor::idx()
858 {
859         return cursor().idx_;
860 }
861
862
863 MathCursor::pos_type MathCursor::pos() const
864 {
865         return cursor().pos_;
866 }
867
868
869 MathCursor::pos_type & MathCursor::pos()
870 {
871         return cursor().pos_;
872 }
873
874
875 bool MathCursor::inMacroMode() const
876 {
877         return macroNamePos() != -1;
878 }
879
880
881 bool MathCursor::selection() const
882 {
883         return selection_;
884 }
885
886
887 MathArrayInset * MathCursor::enclosingArray(MathCursor::idx_type & idx) const
888 {
889         for (int i = Cursor_.size() - 1; i >= 0; --i) {
890                 MathArrayInset * p = (*Cursor_[i].par_)->asArrayInset();
891                 if (p) {
892                         idx = Cursor_[i].idx_;
893                         return p;
894                 }
895         }
896         return 0;
897 }
898
899
900 void MathCursor::pullArg(bool goright)
901 {
902         dump("pullarg");
903         MathArray a = array();
904
905         MathScriptInset const * p = par()->asScriptInset();
906         if (p) {
907                 // special handling for scripts
908                 const bool up = p->hasUp();
909                 popLeft();
910                 MathScriptInset * q = nextAtom()->asScriptInset();
911                 if (q)
912                         q->removeScript(up);
913                 ++pos();
914                 array().insert(pos(), a);
915                 return;
916         }
917
918         if (popLeft()) {
919                 plainErase();
920                 array().insert(pos(), a);
921                 if (goright) 
922                         pos() += a.size();
923         }
924 }
925
926
927 void MathCursor::normalize() const
928 {
929 #ifdef WITH_WARNINGS
930 #warning This is evil!
931 #endif
932         MathCursor * it = const_cast<MathCursor *>(this);
933
934         if (idx() >= par()->nargs()) {
935                 lyxerr << "this should not really happen - 1: "
936                        << idx() << " " << par()->nargs() << "\n";
937                 dump("error 2");
938         }
939         it->idx()    = min(idx(), par()->nargs() - 1);
940
941         if (pos() > size()) {
942                 lyxerr << "this should not really happen - 2: "
943                         << pos() << " " << size() <<  " in idx: " << it->idx()
944                         << " in atom: '";
945                 MathWriteInfo wi(0, lyxerr, false);
946                 it->par()->write(wi);
947                 lyxerr << "\n";
948                 dump("error 4");
949         }
950         it->pos() = min(pos(), size());
951 }
952
953
954 MathCursor::size_type MathCursor::size() const
955 {
956         return array().size();
957 }
958
959
960 MathCursor::col_type MathCursor::col() const
961 {
962         return par()->col(idx());
963 }
964
965
966 MathCursor::row_type MathCursor::row() const
967 {
968         return par()->row(idx());
969 }
970
971
972 bool MathCursor::hasPrevAtom() const
973 {
974         return pos() > 0;
975 }
976
977
978 bool MathCursor::hasNextAtom() const
979 {
980         return pos() < size();
981 }
982
983
984 MathAtom const & MathCursor::prevAtom() const
985 {
986         lyx::Assert(pos() > 0);
987         return array().at(pos() - 1);
988 }
989
990
991 MathAtom & MathCursor::prevAtom()
992 {
993         lyx::Assert(pos() > 0);
994         return array().at(pos() - 1);
995 }
996
997
998 MathAtom const & MathCursor::nextAtom() const
999 {
1000         lyx::Assert(pos() < size());
1001         return array().at(pos());
1002 }
1003
1004
1005 MathAtom & MathCursor::nextAtom()
1006 {
1007         lyx::Assert(pos() < size());
1008         return array().at(pos());
1009 }
1010
1011
1012 MathArray & MathCursor::array() const
1013 {
1014         static MathArray dummy;
1015
1016         if (idx() >= par()->nargs()) {
1017                 lyxerr << "############  idx_ " << idx() << " not valid\n";
1018                 return dummy;
1019         }
1020
1021         return cursor().cell();
1022 }
1023
1024
1025 MathXArray & MathCursor::xarray() const
1026 {
1027         return cursor().xcell();
1028 }
1029
1030
1031 void MathCursor::idxNext()
1032 {
1033         par()->idxNext(idx(), pos());
1034 }
1035
1036
1037 void MathCursor::idxPrev()
1038 {
1039         par()->idxPrev(idx(), pos());
1040 }
1041
1042
1043 void MathCursor::splitCell()
1044 {
1045         if (idx() == par()->nargs() - 1) 
1046                 return;
1047         MathArray ar = array();
1048         ar.erase(0, pos());
1049         array().erase(pos(), size());
1050         ++idx();
1051         pos() = 0;
1052         array().insert(0, ar);
1053 }
1054
1055
1056 void MathCursor::breakLine()
1057 {
1058         // leave inner cells
1059         while (popRight())
1060                 ;
1061
1062         MathMatrixInset * p = formula()->par()->asMatrixInset();
1063         if (!p)
1064                 return;
1065
1066         if (p->getType() == LM_OT_SIMPLE || p->getType() == LM_OT_EQUATION) {
1067                 p->mutate(LM_OT_EQNARRAY);
1068                 idx() = 0;
1069                 pos() = size();
1070         } else {
1071                 p->addRow(row());
1072
1073                 // split line
1074                 const row_type r = row();
1075                 for (col_type c = col() + 1; c < p->ncols(); ++c) {
1076                         const MathMatrixInset::idx_type i1 = p->index(r, c);
1077                         const MathMatrixInset::idx_type i2 = p->index(r + 1, c);        
1078                         //lyxerr << "swapping cells " << i1 << " and " << i2 << "\n";
1079                         p->cell(i1).swap(p->cell(i2));
1080                 }
1081
1082                 // split cell
1083                 splitCell();
1084                 p->cell(idx()).swap(p->cell(idx() + p->ncols() - 1));
1085         }
1086 }
1087
1088
1089 char MathCursor::valign() const
1090 {
1091         idx_type idx;
1092         MathArrayInset * p = enclosingArray(idx);
1093         return p ? p->valign() : '\0';
1094 }
1095
1096
1097 char MathCursor::halign() const
1098 {
1099         idx_type idx;
1100         MathArrayInset * p = enclosingArray(idx);
1101         return p ? p->halign(idx % p->ncols()) : '\0';
1102 }
1103
1104
1105 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1106 {
1107         MathCursorPos anc = normalAnchor();
1108         if (anc < cursor()) {
1109                 i1 = anc;
1110                 i2 = cursor();
1111         } else {
1112                 i1 = cursor();
1113                 i2 = anc;
1114         }
1115 }
1116
1117
1118 MathCursorPos & MathCursor::cursor()
1119 {
1120         return Cursor_.back();
1121 }
1122
1123
1124 MathCursorPos const & MathCursor::cursor() const
1125 {
1126         return Cursor_.back();
1127 }
1128
1129
1130 int MathCursor::cellXOffset() const
1131 {
1132         return par()->cellXOffset(idx());
1133 }
1134
1135
1136 int MathCursor::cellYOffset() const
1137 {
1138         return par()->cellYOffset(idx());
1139 }
1140
1141
1142 int MathCursor::xpos() const
1143 {
1144         return cellXOffset() + xarray().pos2x(pos());
1145 }
1146
1147
1148 int MathCursor::ypos() const
1149 {
1150         return cellYOffset();
1151 }
1152
1153
1154
1155 void MathCursor::gotoX(int x) 
1156 {
1157         pos() = xarray().x2pos(x - cellXOffset());
1158 }
1159
1160
1161 bool MathCursor::goUp()
1162 {
1163         // first ask the inset if it knows better then we
1164         if (par()->idxUp(idx(), pos()))
1165                 return true;
1166
1167         // leave subscript to the nearest side  
1168         MathScriptInset * p = par()->asScriptInset();
1169         if (p && idx() == 0) {
1170                 if (pos() <= size() / 2)
1171                         popLeft();
1172                 else
1173                         popRight();             
1174                 return true;
1175         }
1176
1177         // if not, apply brute force.
1178         int x0;
1179         int y0;
1180         getPos(x0, y0);
1181         std::vector<MathCursorPos> save = Cursor_;
1182         MathAtom const & out = formula()->par();
1183         y0 -= xarray().ascent();
1184         for (int y = y0 - 4; y > out->yo() - out->ascent(); y -= 4) {
1185                 setPos(x0, y);
1186                 if (save != Cursor_ && xarray().yo() < y0)
1187                         return true;    
1188         }
1189         Cursor_ = save;
1190         return false;
1191 }
1192
1193
1194 bool MathCursor::goDown()
1195 {
1196         // first ask the inset if it knows better then we
1197         if (par()->idxDown(idx(), pos()))
1198                 return true;
1199
1200         // leave superscript to the nearest side        
1201         MathScriptInset * p = par()->asScriptInset();
1202         if (p && idx() == 1) {
1203                 if (pos() <= size() / 2)
1204                         popLeft();
1205                 else
1206                         popRight();             
1207                 return true;
1208         }
1209
1210         // if not, apply brute force.
1211         int x0;
1212         int y0;
1213         getPos(x0, y0);
1214         std::vector<MathCursorPos> save = Cursor_;
1215         MathAtom const & out = formula()->par();
1216         y0 += xarray().descent();
1217         for (int y = y0 + 4; y < out->yo() + out->descent(); y += 4) {
1218                 setPos(x0, y);
1219                 if (save != Cursor_ && xarray().yo() > y0)
1220                         return true;    
1221         }
1222         Cursor_ = save;
1223         return false;
1224 }
1225
1226
1227 bool MathCursor::idxLeft()
1228 {
1229         return par()->idxLeft(idx(), pos());
1230 }
1231
1232
1233 bool MathCursor::idxRight()
1234 {
1235         return par()->idxRight(idx(), pos());
1236 }
1237
1238
1239 void MathCursor::interpret(string const & s)
1240 {
1241         //lyxerr << "interpret 1: '" << s << "'\n";
1242         if (s.empty())
1243                 return;
1244
1245         if (s.size() == 1) {
1246                 interpret(s[0]);
1247                 return;
1248         }
1249
1250         //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
1251         //owner_->getIntl()->getTrans().TranslateAndInsert(s[0], lt);   
1252         //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
1253
1254         if (s.size() > 7 && s.substr(0, 7) == "matrix ") {
1255                 unsigned int m = 1;
1256                 unsigned int n = 1;
1257                 string v_align;
1258                 string h_align;
1259                 istringstream is(s.substr(7).c_str());
1260                 is >> m >> n >> v_align >> h_align;
1261                 m = std::max(1u, m);
1262                 n = std::max(1u, n);
1263                 v_align += 'c';
1264                 niceInsert(MathAtom(new MathArrayInset(m, n, v_align[0], h_align)));
1265                 return;
1266         }
1267
1268         if (s == "\\over" || s == "\\choose" || s == "\\atop") {
1269                 MathArray ar = array();
1270                 MathAtom t = createMathInset(s.substr(1));
1271                 t->asNestInset()->cell(0).swap(array());
1272                 pos() = 0;
1273                 niceInsert(t);
1274                 popRight();
1275                 left();
1276                 return;
1277         }
1278
1279         niceInsert(createMathInset(s.substr(1)));
1280 }
1281
1282
1283 void MathCursor::interpret(char c)
1284 {
1285         //lyxerr << "interpret 2: '" << c << "'\n";
1286
1287         if (inMacroMode()) {
1288                 string name = macroName();
1289
1290                 if (name == "\\" && c == '#') {
1291                         insert(c, LM_TC_TEX);
1292                         return;
1293                 }
1294
1295                 if (name == "\\" && c == '\\') {
1296                         backspace();
1297                         interpret("\\backslash");
1298                         return;
1299                 }
1300
1301                 if (name == "\\#" && '1' <= c && c <= '9') {
1302                         insert(c, LM_TC_TEX);
1303                         macroModeClose();
1304                         return;
1305                 }
1306
1307                 if (isalpha(c)) {
1308                         insert(c, LM_TC_TEX);
1309                         return;
1310                 }
1311
1312                 if (name == "\\") {
1313                         insert(c, LM_TC_TEX);
1314                         macroModeClose();
1315                         return;
1316                 }
1317
1318                 macroModeClose();
1319                 return;
1320         }
1321
1322         // no macro mode
1323         if (c == '^' || c == '_') {
1324                 const bool up = (c == '^');
1325                 selCut();
1326                 if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1327                         prevAtom()->asScriptInset()->ensure(up);
1328                         pushRight(prevAtom());
1329                         idx() = up;
1330                         pos() = size();
1331                 } else if (hasNextAtom() && nextAtom()->asScriptInset()) {
1332                         nextAtom()->asScriptInset()->ensure(up);
1333                         pushLeft(nextAtom());
1334                         idx() = up;
1335                         pos() = 0;
1336                 } else {
1337                         plainInsert(MathAtom(new MathScriptInset(up)));
1338                         prevAtom()->asScriptInset()->ensure(up);
1339                         pushRight(prevAtom());
1340                         idx() = up;
1341                         pos() = 0;
1342                 }
1343                 selPaste();
1344                 dump("1");
1345                 return;
1346         }
1347
1348         if (selection_)
1349                 selDel();
1350
1351         if (lastcode_ == LM_TC_TEXTRM) {
1352                 insert(c, LM_TC_TEXTRM);
1353                 return;
1354         }
1355
1356         if (c == ' ') {
1357                 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1358                         prevAtom()->asSpaceInset()->incSpace();
1359                         return;
1360                 }
1361
1362                 if (mathcursor->popRight())
1363                         return;
1364
1365 #warning look here
1366                         // this would not work if the inset is in an table!
1367                         //bv->text->cursorRight(bv, true);
1368                         //result = FINISHED;
1369                 return;
1370         }
1371
1372         if (strchr("{}", c)) {
1373                 insert(c, LM_TC_TEX);
1374                 return;
1375         }
1376
1377         if (strchr("#$%", c)) {
1378                 insert(MathAtom(new MathSpecialCharInset(c)));  
1379                 lastcode_ = LM_TC_VAR;
1380                 return;
1381         }
1382
1383         if (isalpha(c) && lastcode_ == LM_TC_GREEK) {
1384                 insert(c, LM_TC_VAR);
1385                 return; 
1386         }
1387
1388         if (isalpha(c) && lastcode_ == LM_TC_GREEK1) {
1389                 insert(c, LM_TC_VAR);
1390                 lastcode_ = LM_TC_VAR;
1391                 return; 
1392         }
1393
1394         if (c == '\\') {
1395                 insert(c, LM_TC_TEX);
1396                 //bv->owner()->message(_("TeX mode"));
1397                 return; 
1398         }
1399
1400         // no special circumstances, so insert the character without any fuss
1401         insert(c, LM_TC_MIN);
1402 }
1403
1404
1405
1406 ////////////////////////////////////////////////////////////////////////
1407
1408
1409 bool operator==(MathCursorPos const & ti, MathCursorPos const & it)
1410 {
1411         return ti.par_ == it.par_ && ti.idx_ == it.idx_ && ti.pos_ == it.pos_;
1412 }
1413
1414
1415 bool operator<(MathCursorPos const & ti, MathCursorPos const & it)
1416 {
1417         if (ti.par_ != it.par_) {
1418                 lyxerr << "can't compare cursor and anchor in different insets\n";
1419                 return true;
1420         }
1421         if (ti.idx_ != it.idx_)
1422                 return ti.idx_ < it.idx_;
1423         return ti.pos_ < it.pos_;
1424 }
1425
1426
1427 MathArray & MathCursorPos::cell(MathCursor::idx_type idx) const
1428 {
1429         return (*par_)->cell(idx);
1430 }
1431
1432
1433 MathArray & MathCursorPos::cell() const
1434 {
1435         return (*par_)->cell(idx_);
1436 }
1437
1438
1439 MathXArray & MathCursorPos::xcell(MathCursor::idx_type idx) const
1440 {
1441         return (*par_)->xcell(idx);
1442 }
1443
1444
1445 MathXArray & MathCursorPos::xcell() const
1446 {
1447         return (*par_)->xcell(idx_);
1448 }
1449
1450
1451 MathCursorPos MathCursor::normalAnchor() const
1452 {
1453         // use Anchor on the same level as Cursor
1454         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1455         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1456                 // anchor is behind cursor -> move anchor behind the inset
1457                 ++normal.pos_;
1458         }
1459         return normal;
1460 }
1461
1462