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