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