]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
63e4f8306371027c4118520250d82da1e09d95a8
[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 #include <config.h>
19
20 #ifdef __GNUG__
21 #pragma implementation
22 #endif
23
24 #include "support/lstrings.h"
25 #include "support/LAssert.h"
26 #include "debug.h"
27 #include "LColor.h"
28 #include "Painter.h"
29 #include "math_cursor.h"
30 #include "formulabase.h"
31 #include "math_arrayinset.h"
32 #include "math_braceinset.h"
33 #include "math_boxinset.h"
34 #include "math_casesinset.h"
35 #include "math_charinset.h"
36 #include "math_deliminset.h"
37 #include "math_factory.h"
38 #include "math_hullinset.h"
39 #include "math_iterator.h"
40 #include "math_mathmlstream.h"
41 #include "math_parser.h"
42 #include "math_replace.h"
43 #include "math_scriptinset.h"
44 #include "math_spaceinset.h"
45 #include "math_specialcharinset.h"
46 #include "math_support.h"
47
48 #include <algorithm>
49 #include <cctype>
50
51 #define FILEDEBUG 0
52
53 using std::endl;
54 using std::min;
55 using std::max;
56 using std::swap;
57 using std::isalnum;
58
59 namespace {
60
61 struct Selection
62 {
63         typedef MathInset::col_type col_type;
64         typedef MathInset::row_type row_type;
65         typedef MathInset::idx_type idx_type;
66
67         Selection()
68                 : data_(1, 1)
69         {}
70
71         void region(MathCursorPos const & i1, MathCursorPos const & i2,
72                 row_type & r1, row_type & r2, col_type & c1, col_type & c2)
73         {
74                 MathInset * p = i1.par_;
75                 c1 = p->col(i1.idx_);
76                 c2 = p->col(i2.idx_);
77                 if (c1 > c2)
78                         std::swap(c1, c2);
79                 r1 = p->row(i1.idx_);
80                 r2 = p->row(i2.idx_);
81                 if (r1 > r2)
82                         std::swap(r1, r2);
83         }
84
85         void grab(MathCursor const & cursor)
86         {
87                 MathCursorPos i1;
88                 MathCursorPos i2;
89                 cursor.getSelection(i1, i2); 
90                 // shouldn'tt we assert on i1.par_ == i2.par_?
91                 if (i1.idx_ == i2.idx_) {
92                         data_ = MathGridInset(1, 1);
93                         data_.cell(0) = MathArray(i1.cell(), i1.pos_, i2.pos_);
94                 } else {
95                         row_type r1, r2;
96                         col_type c1, c2;
97                         region(i1, i2, r1, r2, c1, c2); 
98                         data_ = MathGridInset(c2 - c1 + 1, r2 - r1 + 1);
99                         for (row_type row = 0; row < data_.nrows(); ++row) 
100                                 for (col_type col = 0; col < data_.ncols(); ++col) {
101                                         idx_type i = i1.par_->index(row + r1, col + c1);
102                                         data_.cell(data_.index(row, col)) = i1.par_->cell(i);
103                                 }
104                 }
105         }
106
107         void erase(MathCursor & cursor)
108         {
109                 MathCursorPos i1;
110                 MathCursorPos i2;
111                 cursor.getSelection(i1, i2); 
112                 if (i1.idx_ == i2.idx_)
113                         i1.cell().erase(i1.pos_, i2.pos_);
114                 else {
115                         MathInset * p = i1.par_;
116                         row_type r1, r2;
117                         col_type c1, c2;
118                         region(i1, i2, r1, r2, c1, c2); 
119                         for (row_type row = r1; row <= r2; ++row) 
120                                 for (col_type col = c1; col <= c2; ++col)
121                                         p->cell(p->index(row, col)).erase();
122                 }
123                 cursor.cursor() = i1;
124         }
125
126         void paste(MathCursor & cursor) const
127         {
128                 if (data_.nargs() == 1) {
129                         // single cell/part of cell
130                         cursor.insert(data_.cell(0));
131                 } else {
132                         // mulitple cells
133                         idx_type idx;
134                         MathGridInset * p = cursor.enclosingGrid(idx);
135                         col_type const numcols = min(data_.ncols(), p->ncols() - p->col(idx));
136                         row_type const numrows = min(data_.nrows(), p->nrows() - p->row(idx));
137                         for (row_type row = 0; row < numrows; ++row) 
138                                 for (col_type col = 0; col < numcols; ++col) {
139                                         idx_type i = p->index(row + p->row(idx), col + p->col(idx));
140                                         p->cell(i).push_back(data_.cell(data_.index(row, col)));
141                                 }
142                 }
143         }
144
145         // glues selection to one cell
146         MathArray glue() const
147         {
148                 MathArray ar;
149                 for (unsigned i = 0; i < data_.nargs(); ++i)
150                         ar.push_back(data_.cell(i));
151                 return ar;
152         }
153
154         void clear()
155         {
156                 data_ = MathGridInset(1, 1);
157         }
158
159         MathGridInset data_;
160 };
161
162
163 Selection theSelection;
164
165
166
167 }
168
169
170 MathCursor::MathCursor(InsetFormulaBase * formula, bool left)
171         : formula_(formula), lastcode_(LM_TC_VAR), selection_(false)
172 {
173         left ? first() : last();
174 }
175
176
177 void MathCursor::push(MathAtom & t)
178 {
179         Cursor_.push_back(MathCursorPos(t.nucleus()));
180 }
181
182
183 void MathCursor::pushLeft(MathAtom & t)
184 {
185         //cerr << "Entering atom "; t->write(cerr, false); cerr << " left\n";
186         push(t);
187         t->idxFirst(idx(), pos());
188 }
189
190
191 void MathCursor::pushRight(MathAtom & t)
192 {
193         //cerr << "Entering atom "; t->write(cerr, false); cerr << " right\n";
194         posLeft();
195         push(t);
196         t->idxLast(idx(), pos());
197 }
198
199
200 bool MathCursor::popLeft()
201 {
202         //cerr << "Leaving atom "; par()->write(cerr, false); cerr << " left\n";
203         if (Cursor_.size() <= 1)
204                 return false;
205         if (par()->asScriptInset())
206                 par()->asScriptInset()->removeEmptyScripts();
207         Cursor_.pop_back();
208         return true;
209 }
210
211
212 bool MathCursor::popRight()
213 {
214         //cerr << "Leaving atom "; par()->write(cerr, false); cerr << " right\n";
215         if (Cursor_.size() <= 1)
216                 return false;
217         if (par()->asScriptInset())
218                 par()->asScriptInset()->removeEmptyScripts();
219         Cursor_.pop_back();
220         posRight();
221         return true;
222 }
223
224
225
226 #if FILEDEBUG
227         void MathCursor::dump(char const * what) const
228         {
229                 lyxerr << "MC: " << what << "\n";
230                 lyxerr << " Cursor: " << Cursor_.size() << "\n";
231                 for (unsigned i = 0; i < Cursor_.size(); ++i)
232                         lyxerr << "    i: " << i << " " << Cursor_[i] << "\n";
233                 lyxerr << " Anchor: " << Anchor_.size() << "\n";
234                 for (unsigned i = 0; i < Anchor_.size(); ++i)
235                         lyxerr << "    i: " << i << " " << Anchor_[i] << "\n";
236                 lyxerr  << " sel: " << selection_ << "\n";
237         }
238 #else
239         void MathCursor::dump(char const *) const {}
240 #endif
241
242
243 UpdatableInset * MathCursor::asHyperActiveInset() const
244 {
245         return par()->asHyperActiveInset();
246 }
247
248
249 bool MathCursor::isInside(MathInset const * p) const
250 {
251         for (unsigned i = 0; i < Cursor_.size(); ++i) 
252                 if (Cursor_[i].par_ == p) 
253                         return true;
254         return false;
255 }
256
257
258 bool MathCursor::openable(MathAtom const & t, bool sel) const
259 {
260         if (t->isHyperActive())
261                 return true;
262
263         if (!t->isActive())
264                 return false;
265
266         if (t->asScriptInset())
267                 return false;
268
269         if (sel) {
270                 // we can't move into anything new during selection
271                 if (Cursor_.size() == Anchor_.size())
272                         return false;
273                 if (t.nucleus() != Anchor_[Cursor_.size()].par_)
274                         return false;
275         }
276         return true;
277 }
278
279
280 bool MathCursor::posLeft()
281 {
282         if (pos() == 0)
283                 return false;
284         --pos();
285         return true;
286 }
287
288
289 bool MathCursor::posRight()
290 {
291         if (pos() == size())
292                 return false;
293         ++pos();
294         return true;
295 }
296
297
298 bool MathCursor::left(bool sel)
299 {
300         dump("Left 1");
301         if (inMacroMode()) {
302                 macroModeClose();
303                 lastcode_ = LM_TC_VAR;
304                 return true;
305         }
306         selHandle(sel);
307         lastcode_ = LM_TC_VAR;
308
309         if (hasPrevAtom() && openable(prevAtom(), sel)) {
310                 if (prevAtom()->isHyperActive()) {
311                         lyxerr << "entering hyperactive inset\n";
312                 }
313                 pushRight(prevAtom());
314                 return true;
315         } 
316
317         return posLeft() || idxLeft() || popLeft() || selection_;
318 }
319
320
321 bool MathCursor::right(bool sel)
322 {
323         dump("Right 1");
324         if (inMacroMode()) {
325                 macroModeClose();
326                 lastcode_ = LM_TC_VAR;
327                 return true;
328         }
329         selHandle(sel);
330         lastcode_ = LM_TC_VAR;
331
332         if (hasNextAtom() && openable(nextAtom(), sel)) {
333                 if (nextAtom()->isHyperActive()) {
334                         lyxerr << "entering hyperactive inset\n";
335                         int x, y;
336                         getPos(x, y);
337                         nextAtom()->edit(formula()->view(), x, y, 0);
338                 }
339                 pushLeft(nextAtom());
340                 return true;
341         }
342
343         return posRight() || idxRight() || popRight() || selection_;
344 }
345
346
347 void MathCursor::first()
348 {
349         Cursor_.clear();
350         pushLeft(formula_->par());
351 }
352
353
354 void MathCursor::last()
355 {
356         first();
357         end();
358 }
359
360
361 bool positionable(MathCursor::cursor_type const & cursor,
362                   MathCursor::cursor_type const & anchor)
363 {
364         // avoid deeper nested insets when selecting
365         if (cursor.size() > anchor.size())
366                 return false;
367
368         // anchor might be deeper, should have same path then
369         for (MathCursor::cursor_type::size_type i = 0; i < cursor.size(); ++i)
370                 if (cursor[i].par_ != anchor[i].par_)
371                         return false;
372
373         // position should be ok.
374         return true;
375 }
376
377
378 void MathCursor::setPos(int x, int y)
379 {
380         dump("setPos 1");
381         bool res = bruteFind(x, y,
382                 formula()->xlow(), formula()->xhigh(),
383                 formula()->ylow(), formula()->yhigh());
384         if (!res) {
385                 // this ccan happen on creation of "math-display"
386                 dump("setPos 1.5");
387                 first();
388         }
389         dump("setPos 2");
390 }
391
392
393
394 void MathCursor::home(bool sel)
395 {
396         dump("home 1");
397         selHandle(sel);
398         macroModeClose();
399         lastcode_ = LM_TC_VAR;
400         if (!par()->idxHome(idx(), pos())) 
401                 popLeft();
402         dump("home 2");
403 }
404
405
406 void MathCursor::end(bool sel)
407 {
408         dump("end 1");
409         selHandle(sel);
410         macroModeClose();
411         lastcode_ = LM_TC_VAR;
412         if (!par()->idxEnd(idx(), pos()))
413                 popRight();
414         dump("end 2");
415 }
416
417
418 void MathCursor::plainErase()
419 {
420         array().erase(pos());
421 }
422
423
424 void MathCursor::plainInsert(MathAtom const & t)
425 {
426         array().insert(pos(), t);
427         ++pos();
428 }
429
430
431 void MathCursor::insert(char c, MathTextCodes t)
432 {
433         //lyxerr << "inserting '" << c << "'\n";
434         plainInsert(MathAtom(new MathCharInset(c, t)));
435 }
436
437
438 void MathCursor::insert(MathAtom const & t)
439 {
440         macroModeClose();
441
442         if (selection_) {
443                 if (t->nargs())
444                         selCut();
445                 else
446                         selDel();
447         }
448
449         plainInsert(t);
450 }
451
452
453 void MathCursor::niceInsert(MathAtom const & t) 
454 {
455         selCut();
456         insert(t); // inserting invalidates the pointer!
457         MathAtom const & p = prevAtom();
458         if (p->nargs()) {
459                 posLeft();
460                 right();  // do not push for e.g. MathSymbolInset
461                 selPaste();
462         }
463 }
464
465
466 void MathCursor::insert(MathArray const & ar)
467 {
468         macroModeClose();
469         if (selection_)
470                 selCut();
471
472         array().insert(pos(), ar);
473         pos() += ar.size();
474 }
475
476
477 void MathCursor::paste(MathArray const & ar)
478 {
479         Anchor_ = Cursor_;
480         selection_ = true;
481         array().insert(pos(), ar);
482         pos() += ar.size();
483 }
484
485
486 void MathCursor::backspace()
487 {
488         if (pos() == 0) {
489                 pullArg(false);
490                 return;
491         }       
492
493         if (selection_) {
494                 selDel();
495                 return;
496         }
497
498         MathScriptInset * p = prevAtom()->asScriptInset();
499         if (p) {
500                 p->removeScript(p->hasUp());
501                 // Don't delete if there is anything left 
502                 if (p->hasUp() || p->hasDown())
503                         return;
504         }
505
506         --pos();
507         plainErase();
508 }
509
510
511 void MathCursor::erase()
512 {
513         if (inMacroMode())
514                 return;
515
516         if (selection_) {
517                 selDel();
518                 return;
519         }
520
521         // delete empty cells if necessary
522         if (array().empty()) {
523                 bool popit;
524                 bool removeit;
525                 par()->idxDelete(idx(), popit, removeit);
526                 if (popit && popLeft() && removeit)
527                         plainErase();
528                 return;
529         }
530
531         if (pos() == size())
532                 return;
533
534         MathScriptInset * p = nextAtom()->asScriptInset();
535         if (p) {
536                 p->removeScript(p->hasUp());
537                 // Don't delete if there is anything left 
538                 if (p->hasUp() || p->hasDown())
539                         return;
540         }
541
542         plainErase();
543 }
544
545
546 void MathCursor::delLine()
547 {
548         macroModeClose();
549
550         if (selection_) {
551                 selDel();
552                 return;
553         }
554
555         if (par()->nrows() > 1) {
556                 // grid are the only things with more than one row...
557                 lyx::Assert(par()->asGridInset());
558                 par()->asGridInset()->delRow(hullRow());
559         }
560
561         if (idx() > par()->nargs())
562                 idx() = par()->nargs();
563
564         if (pos() > size())
565                 pos() = size();
566 }
567
568
569 bool MathCursor::up(bool sel)
570 {
571         dump("up 1");
572         macroModeClose();
573         selHandle(sel);
574         cursor_type save = Cursor_;
575         if (goUpDown(true))
576                 return true;
577         Cursor_ = save;
578         return selection_;
579 }
580
581
582 bool MathCursor::down(bool sel)
583 {
584         dump("down 1");
585         macroModeClose();
586         selHandle(sel);
587         cursor_type save = Cursor_;
588         if (goUpDown(false))
589                 return true;
590         Cursor_ = save;
591         return 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 MathInset * 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()
900 {
901         // rebreak
902         {
903                 MathIterator it = ibegin(formula()->par().nucleus());
904                 MathIterator et = iend(formula()->par().nucleus());
905                 for ( ; it != et; ++it) 
906                         if (it.par()->asBoxInset())
907                                 it.par()->asBoxInset()->rebreak();
908         }
909
910         if (idx() >= par()->nargs()) {
911                 lyxerr << "this should not really happen - 1: "
912                        << idx() << " " << par()->nargs() << "\n";
913                 dump("error 2");
914         }
915         idx() = min(idx(), par()->nargs() - 1);
916
917         if (pos() > size()) {
918                 lyxerr << "this should not really happen - 2: "
919                         << pos() << " " << size() <<  " in idx: " << idx()
920                         << " in atom: '";
921                 WriteStream wi(lyxerr, false);
922                 par()->write(wi);
923                 lyxerr << "\n";
924                 dump("error 4");
925         }
926         pos() = min(pos(), size());
927 }
928
929
930 MathCursor::size_type MathCursor::size() const
931 {
932         return array().size();
933 }
934
935
936 MathCursor::col_type MathCursor::hullCol() const
937 {
938         return Cursor_[0].par_->asGridInset()->col(Cursor_[0].idx_);
939 }
940
941
942 MathCursor::row_type MathCursor::hullRow() const
943 {
944         return Cursor_[0].par_->asGridInset()->row(Cursor_[0].idx_);
945 }
946
947
948 bool MathCursor::hasPrevAtom() const
949 {
950         return pos() > 0;
951 }
952
953
954 bool MathCursor::hasNextAtom() const
955 {
956         return pos() < size();
957 }
958
959
960 MathAtom const & MathCursor::prevAtom() const
961 {
962         lyx::Assert(pos() > 0);
963         return array().at(pos() - 1);
964 }
965
966
967 MathAtom & MathCursor::prevAtom()
968 {
969         lyx::Assert(pos() > 0);
970         return array().at(pos() - 1);
971 }
972
973
974 MathAtom const & MathCursor::nextAtom() const
975 {
976         lyx::Assert(pos() < size());
977         return array().at(pos());
978 }
979
980
981 MathAtom & MathCursor::nextAtom()
982 {
983         lyx::Assert(pos() < size());
984         return array().at(pos());
985 }
986
987
988 MathArray & MathCursor::array() const
989 {
990         static MathArray dummy;
991
992         if (idx() >= par()->nargs()) {
993                 lyxerr << "############  idx_ " << idx() << " not valid\n";
994                 return dummy;
995         }
996
997         if (Cursor_.size() == 0) {
998                 lyxerr << "############  Cursor_.size() == 0 not valid\n";
999                 return dummy;
1000         }
1001
1002         return cursor().cell();
1003 }
1004
1005
1006 MathXArray & MathCursor::xarray() const
1007 {
1008         static MathXArray dummy;
1009
1010         if (Cursor_.size() == 0) {
1011                 lyxerr << "############  Cursor_.size() == 0 not valid\n";
1012                 return dummy;
1013         }
1014
1015         return cursor().xcell();
1016 }
1017
1018
1019 void MathCursor::idxNext()
1020 {
1021         par()->idxNext(idx(), pos());
1022 }
1023
1024
1025 void MathCursor::idxPrev()
1026 {
1027         par()->idxPrev(idx(), pos());
1028 }
1029
1030
1031 void MathCursor::splitCell()
1032 {
1033         if (idx() + 1 == par()->nargs()) 
1034                 return;
1035         MathArray ar = array();
1036         ar.erase(0, pos());
1037         array().erase(pos(), size());
1038         ++idx();
1039         pos() = 0;
1040         array().insert(0, ar);
1041 }
1042
1043
1044 void MathCursor::breakLine()
1045 {
1046         // leave inner cells
1047         while (popRight())
1048                 ;
1049
1050         MathHullInset * p = formula()->par()->asHullInset();
1051         if (!p)
1052                 return;
1053
1054         if (p->getType() == LM_OT_SIMPLE || p->getType() == LM_OT_EQUATION) {
1055                 p->mutate(LM_OT_EQNARRAY);
1056                 idx() = 0;
1057                 pos() = size();
1058         } else {
1059                 p->addRow(hullRow());
1060
1061                 // split line
1062                 const row_type r = hullRow();
1063                 for (col_type c = hullCol() + 1; c < p->ncols(); ++c)
1064                         p->cell(p->index(r, c)).swap(p->cell(p->index(r + 1, c)));
1065
1066                 // split cell
1067                 splitCell();
1068                 p->cell(idx()).swap(p->cell(idx() + p->ncols() - 1));
1069         }
1070 }
1071
1072
1073 //void MathCursor::readLine(MathArray & ar) const
1074 //{
1075 //      idx_type base = row() * par()->ncols();
1076 //      for (idx_type off = 0; off < par()->ncols(); ++off)
1077 //              ar.push_back(par()->cell(base + off));
1078 //}
1079
1080
1081 char MathCursor::valign() const
1082 {
1083         idx_type idx;
1084         MathGridInset * p = enclosingGrid(idx);
1085         return p ? p->valign() : '\0';
1086 }
1087
1088
1089 char MathCursor::halign() const
1090 {
1091         idx_type idx;
1092         MathGridInset * p = enclosingGrid(idx);
1093         return p ? p->halign(idx % p->ncols()) : '\0';
1094 }
1095
1096
1097 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1098 {
1099         MathCursorPos anc = normalAnchor();
1100         if (anc < cursor()) {
1101                 i1 = anc;
1102                 i2 = cursor();
1103         } else {
1104                 i1 = cursor();
1105                 i2 = anc;
1106         }
1107 }
1108
1109
1110 MathCursorPos & MathCursor::cursor()
1111 {
1112         lyx::Assert(Cursor_.size());
1113         return Cursor_.back();
1114 }
1115
1116
1117 MathCursorPos const & MathCursor::cursor() const
1118 {
1119         lyx::Assert(Cursor_.size());
1120         return Cursor_.back();
1121 }
1122
1123
1124 bool MathCursor::goUpDown(bool up)
1125 {
1126         int xlow, xhigh, ylow, yhigh;
1127
1128   int xo, yo;
1129         getPos(xo, yo);
1130
1131         // try current cell first
1132         xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1133         if (up)
1134                 yhigh = yo - 4;
1135         else
1136                 ylow = yo + 4;
1137         if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh))
1138                 return true;
1139
1140         // try to find an inset that knows better then we
1141         while (1) {
1142                 // we found a cell that think something "below" us.
1143                 if (up) {
1144                         if (par()->idxUp(idx()))
1145                                 break;
1146                 } else {
1147                         if (par()->idxDown(idx()))
1148                                 break;
1149                 }
1150
1151                 if (!popLeft()) {
1152                         // no such inset found, just take something "above"
1153                         return
1154                                 bruteFind(xo, yo,
1155                                         formula()->xlow(),
1156                                         formula()->xhigh(),
1157                                         up ? formula()->ylow() : yo + 4,
1158                                         up ? yo - 4 : formula()->yhigh()
1159                                 );
1160                 }
1161         }
1162         xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1163         bruteFind(xo, yo, xlow, xhigh, ylow, yhigh);
1164         return true;
1165 }
1166
1167
1168 bool MathCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1169 {
1170         cursor_type best_cursor;
1171         double best_dist = 1e10;
1172
1173         MathIterator it = ibegin(formula()->par().nucleus());
1174         MathIterator et = iend(formula()->par().nucleus());
1175         for ( ; it != et; ++it) {
1176                 // avoid invalid nesting hen selecting
1177                 if (selection_ && !positionable(it.cursor(), Anchor_))
1178                         continue;
1179                 int xo = it.position().xpos();
1180                 int yo = it.position().ypos();
1181                 if (xlow - 2 <= xo && xo <= xhigh + 2 &&
1182                     ylow - 2 <= yo && yo <= yhigh + 2)
1183                 {
1184                         double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1185                         if (d < best_dist) {
1186                                 best_dist   = d;
1187                                 best_cursor = it.cursor();
1188                         }
1189                 }
1190         }
1191         if (best_dist < 1e10)
1192                 Cursor_ = best_cursor;
1193         return best_dist < 1e10;
1194 }
1195
1196
1197 bool MathCursor::idxLeft()
1198 {
1199         return par()->idxLeft(idx(), pos());
1200 }
1201
1202
1203 bool MathCursor::idxRight()
1204 {
1205         return par()->idxRight(idx(), pos());
1206 }
1207
1208
1209 bool MathCursor::interpret(string const & s)
1210 {
1211         //lyxerr << "interpret 1: '" << s << "'\n";
1212         if (s.empty())
1213                 return true;
1214
1215         if (s.size() == 1)
1216                 return interpret(s[0]);
1217
1218         //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
1219         //owner_->getIntl()->getTrans().TranslateAndInsert(s[0], lt);   
1220         //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
1221
1222         if (s.size() >= 5 && s.substr(0, 5) == "cases") {
1223                 unsigned int n = 1;
1224                 istringstream is(s.substr(5).c_str());
1225                 is >> n;
1226                 n = std::max(1u, n);
1227                 niceInsert(MathAtom(new MathCasesInset(n)));
1228                 return true;
1229         }
1230
1231         if (s.size() >= 6 && s.substr(0, 6) == "matrix") {
1232                 unsigned int m = 1;
1233                 unsigned int n = 1;
1234                 string v_align;
1235                 string h_align;
1236                 istringstream is(s.substr(6).c_str());
1237                 is >> m >> n >> v_align >> h_align;
1238                 m = std::max(1u, m);
1239                 n = std::max(1u, n);
1240                 v_align += 'c';
1241                 niceInsert(MathAtom(new MathArrayInset(m, n, v_align[0], h_align)));
1242                 return true;
1243         }
1244
1245         if (s.size() >= 7 && s.substr(0, 7) == "replace") {
1246                 ReplaceData rep;
1247                 istringstream is(s.substr(7).c_str());
1248                 string from, to;
1249                 is >> from >> to;
1250                 mathed_parse_cell(rep.from, from);
1251                 mathed_parse_cell(rep.to, to);
1252                 lyxerr << "replacing '" << from << "' with '" << to << "'\n";
1253                 par()->replace(rep);
1254                 return true;
1255         }
1256
1257         if (s == "\\over" || s == "\\choose" || s == "\\atop") {
1258                 MathArray ar = array();
1259                 MathAtom t(createMathInset(s.substr(1)));
1260                 t->asNestInset()->cell(0).swap(array());
1261                 pos() = 0;
1262                 niceInsert(t);
1263                 popRight();
1264                 left();
1265                 return true;
1266         }
1267
1268         latexkeys const * l = in_word_set(s.substr(1));
1269         if (l && (l->token == LM_TK_FONT || l->token == LM_TK_OLDFONT)) {
1270                 lastcode_ = static_cast<MathTextCodes>(l->id);
1271                 return true;
1272         }
1273
1274         niceInsert(createMathInset(s.substr(1)));
1275         return true;
1276 }
1277
1278
1279 bool MathCursor::script(bool up)
1280 {
1281         macroModeClose();
1282         selCut();
1283         if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1284                 prevAtom()->asScriptInset()->ensure(up);
1285                 pushRight(prevAtom());
1286                 idx() = up;
1287                 pos() = size();
1288         } else if (hasNextAtom() && nextAtom()->asScriptInset()) {
1289                 nextAtom()->asScriptInset()->ensure(up);
1290                 pushLeft(nextAtom());
1291                 idx() = up;
1292                 pos() = 0;
1293         } else {
1294                 plainInsert(MathAtom(new MathScriptInset(up)));
1295                 prevAtom()->asScriptInset()->ensure(up);
1296                 pushRight(prevAtom());
1297                 idx() = up;
1298                 pos() = 0;
1299         }
1300         selPaste();
1301         dump("1");
1302         return true;
1303 }
1304
1305
1306 bool MathCursor::interpret(char c)
1307 {
1308
1309         // Removed super/subscript handling from here  to ::script -MV
1310
1311         // handle macroMode
1312         if (inMacroMode()) {
1313                 string name = macroName();
1314
1315                 if (name == "\\" && c == '#') {
1316                         insert(c, LM_TC_TEX);
1317                         return true;
1318                 }
1319
1320                 if (name == "\\" && c == '\\') {
1321                         backspace();
1322                         interpret("\\backslash");
1323                         return true;
1324                 }
1325
1326                 if (name == "\\#" && '1' <= c && c <= '9') {
1327                         insert(c, LM_TC_TEX);
1328                         macroModeClose();
1329                         return true;
1330                 }
1331
1332                 if (isalpha(c)) {
1333                         insert(c, LM_TC_TEX);
1334                         return true;
1335                 }
1336
1337                 if (name == "\\") {
1338                         insert(c, LM_TC_TEX);
1339                         macroModeClose();
1340                         return true;
1341                 }
1342
1343                 macroModeClose();
1344                 return true;
1345         }
1346
1347         if (selection_) {
1348                 selClear();
1349                 if (c == ' ')
1350                         return true;
1351                 // fall through in the other cases
1352         }
1353
1354         if (lastcode_ == LM_TC_TEXTRM || par()->asBoxInset()) {
1355                 // suppress direct insertion of two spaces in a row
1356                 // the still allows typing  '<space>a<space>' and deleting the 'a', but
1357                 // it is better than nothing...
1358                 if (c == ' ' && hasPrevAtom() && prevAtom()->getChar() == ' ')
1359                         return true;
1360                 insert(c, LM_TC_TEXTRM);
1361                 return true;
1362         }
1363
1364         if (c == ' ') {
1365                 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1366                         prevAtom()->asSpaceInset()->incSpace();
1367                         return true;
1368                 }
1369                 if (popRight())
1370                         return true;
1371                 // if are at the very end, leave the formula
1372                 return pos() != size();
1373         }
1374
1375 /*
1376         if (strchr("{}", c)) {
1377                 insert(c, LM_TC_TEX);
1378                 return true;
1379         }
1380 */
1381
1382         if (c == '{') {
1383                 niceInsert(MathAtom(new MathBraceInset));
1384                 return true;
1385         }
1386
1387         if (c == '}') {
1388                 return true;
1389         }
1390
1391         if (strchr("#$%", c)) {
1392                 insert(MathAtom(new MathSpecialCharInset(c)));  
1393                 lastcode_ = LM_TC_VAR;
1394                 return true;
1395         }
1396
1397         if (isalpha(c) && lastcode_ == LM_TC_GREEK) {
1398                 insert(c, LM_TC_VAR);
1399                 return true;
1400         }
1401
1402         if (isalpha(c) && lastcode_ == LM_TC_GREEK1) {
1403                 insert(c, LM_TC_VAR);
1404                 lastcode_ = LM_TC_VAR;
1405                 return true;
1406         }
1407
1408         if (c == '\\') {
1409                 insert(c, LM_TC_TEX);
1410                 //bv->owner()->message(_("TeX mode"));
1411                 return true;    
1412         }
1413
1414         // no special circumstances, so insert the character without any fuss
1415         insert(c, lastcode_);
1416         lastcode_ = LM_TC_MIN;
1417         return true;
1418 }
1419
1420
1421
1422 MathCursorPos MathCursor::normalAnchor() const
1423 {
1424         if (Anchor_.size() < Cursor_.size()) {
1425                 Anchor_ = Cursor_;
1426                 lyxerr << "unusual Anchor size\n";
1427                 dump("1");
1428         }
1429         //lyx::Assert(Anchor_.size() >= Cursor_.size());
1430         // use Anchor on the same level as Cursor
1431         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1432         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1433                 // anchor is behind cursor -> move anchor behind the inset
1434                 ++normal.pos_;
1435         }
1436         return normal;
1437 }
1438
1439
1440 void MathCursor::stripFromLastEqualSign()
1441 {
1442         // find position of last '=' in the array
1443         MathArray & ar = cursor().cell();
1444         MathArray::const_iterator et = ar.end();
1445         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
1446                 if ((*it)->getChar() == '=')
1447                         et = it;
1448
1449         // delete everything behind this position
1450         ar.erase(et - ar.begin(), ar.size());
1451         pos() = ar.size(); 
1452 }
1453
1454
1455 void MathCursor::setSelection(cursor_type const & where, size_type n)
1456 {
1457         selection_ = true;
1458         Anchor_ = where;
1459         Cursor_ = where;
1460         cursor().pos_ += n;
1461 }