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