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