]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
updates to latexfeatures stuff; allow empty \document_path
[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_MIN), 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_MIN;
304                 return true;
305         }
306         selHandle(sel);
307         lastcode_ = LM_TC_MIN;
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_MIN;
327                 return true;
328         }
329         selHandle(sel);
330         lastcode_ = LM_TC_MIN;
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_MIN;
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_MIN;
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 MathInset::difference_type MathCursor::macroNamePos() const
621 {
622         for (MathInset::difference_type 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         MathInset::difference_type i = macroNamePos(); 
635         for ( ; i >= 0 && i < int(pos()); ++i) 
636                 s += array().at(i)->getChar();
637         return s;
638 }
639
640
641 void MathCursor::selCopy()
642 {
643         dump("selCopy");
644         if (selection_) {
645                 theSelection.grab(*this);
646                 selClear();
647         }
648 }
649
650
651 void MathCursor::selCut()
652 {
653         dump("selCut");
654         if (selection_) {
655                 theSelection.grab(*this);
656                 theSelection.erase(*this);
657                 selClear();
658         } else {
659                 theSelection.clear();
660         }
661 }
662
663
664 void MathCursor::selDel()
665 {
666         dump("selDel");
667         if (selection_) {
668                 theSelection.erase(*this);
669                 if (pos() > size())
670                         pos() = size();
671                 selClear();
672         }
673 }
674
675
676 void MathCursor::selPaste()
677 {
678         dump("selPaste");
679         theSelection.paste(*this);
680         //theSelection.grab(*this);
681         //selClear();
682 }
683
684
685 void MathCursor::selHandle(bool sel)
686 {
687         if (sel == selection_)
688                 return;
689         //theSelection.clear();
690         Anchor_    = Cursor_;
691         selection_ = sel;
692 }
693
694
695 void MathCursor::selStart()
696 {
697         dump("selStart 1");
698         //theSelection.clear();
699         Anchor_ = Cursor_;
700         selection_ = true;
701         dump("selStart 2");
702 }
703
704
705 void MathCursor::selClear()
706 {
707         dump("selClear 1");
708         selection_ = false;
709         dump("selClear 2");
710 }
711
712
713 void MathCursor::selGet(MathArray & ar)
714 {
715         dump("selGet");
716         if (!selection_)
717                 return;
718
719         theSelection.grab(*this);
720         ar = theSelection.glue();
721 }
722
723
724
725 void MathCursor::drawSelection(Painter & pain) const
726 {
727         if (!selection_)
728                 return;
729
730         MathCursorPos i1;
731         MathCursorPos i2;
732         getSelection(i1, i2);
733
734         if (i1.idx_ == i2.idx_) {
735                 MathXArray & c = i1.xcell();
736                 int x1 = c.xo() + c.pos2x(i1.pos_);
737                 int y1 = c.yo() - c.ascent();
738                 int x2 = c.xo() + c.pos2x(i2.pos_);
739                 int y2 = c.yo() + c.descent();
740                 pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
741         } else {
742                 std::vector<MathInset::idx_type> indices
743                         = i1.par_->idxBetween(i1.idx_, i2.idx_);
744                 for (unsigned i = 0; i < indices.size(); ++i) {
745                         MathXArray & c = i1.xcell(indices[i]);
746                         int x1 = c.xo();
747                         int y1 = c.yo() - c.ascent();
748                         int x2 = c.xo() + c.width();
749                         int y2 = c.yo() + c.descent();
750                         pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
751                 }
752         }
753
754 #if 0
755         // draw anchor if different from selection boundary
756         MathCursorPos anc = Anchor_.back();
757         if (anc != i1 && anc != i2) {
758                 MathXArray & c = anc.xcell();
759                 int x  = c.xo() + c.pos2x(anc.pos_);
760                 int y1 = c.yo() - c.ascent();
761                 int y2 = c.yo() + c.descent();
762                 pain.line(x, y1, x, y2, LColor::math);
763         }
764 #endif
765 }
766
767
768 void MathCursor::handleFont(MathTextCodes t)
769 {
770         macroModeClose();
771         if (selection_) {
772                 MathCursorPos i1;
773                 MathCursorPos i2;
774                 getSelection(i1, i2); 
775                 if (i1.idx_ == i2.idx_) {
776                         MathArray & ar = i1.cell();
777                         for (MathInset::pos_type pos = i1.pos_; pos != i2.pos_; ++pos)
778                                 ar.at(pos)->handleFont(t);
779                 }
780         } else 
781                 lastcode_ = (lastcode_ == t) ? LM_TC_VAR : t;
782 }
783
784
785 void MathCursor::handleDelim(string const & l, string const & r)
786 {
787         handleNest(new MathDelimInset(l, r));
788 }
789
790
791 void MathCursor::handleNest(MathInset * p)
792 {
793         if (selection_) {
794                 selCut();
795                 p->cell(0) = theSelection.glue();
796         }
797         insert(MathAtom(p)); // this invalidates p!
798         pushRight(prevAtom());
799 }
800
801
802 void MathCursor::getPos(int & x, int & y)
803 {
804 #ifdef WITH_WARNINGS
805 #warning This should probably take cellXOffset and cellYOffset into account
806 #endif
807         x = xarray().xo() + xarray().pos2x(pos());
808         y = xarray().yo();
809 }
810
811
812 MathInset * MathCursor::par() const
813 {
814         return cursor().par_;
815 }
816
817
818 InsetFormulaBase * MathCursor::formula()
819 {
820         return formula_;
821 }
822
823
824 MathCursor::idx_type MathCursor::idx() const
825 {
826         return cursor().idx_;
827 }
828
829
830 MathCursor::idx_type & MathCursor::idx()
831 {
832         return cursor().idx_;
833 }
834
835
836 MathCursor::pos_type MathCursor::pos() const
837 {
838         return cursor().pos_;
839 }
840
841
842 MathCursor::pos_type & MathCursor::pos()
843 {
844         return cursor().pos_;
845 }
846
847
848 bool MathCursor::inMacroMode() const
849 {
850         return macroNamePos() != -1;
851 }
852
853
854 bool MathCursor::selection() const
855 {
856         return selection_;
857 }
858
859
860 MathGridInset * MathCursor::enclosingGrid(MathCursor::idx_type & idx) const
861 {
862         for (MathInset::difference_type i = Cursor_.size() - 1; i >= 0; --i) {
863                 MathGridInset * p = Cursor_[i].par_->asGridInset();
864                 if (p) {
865                         idx = Cursor_[i].idx_;
866                         return p;
867                 }
868         }
869         return 0;
870 }
871
872
873 void MathCursor::pullArg(bool goright)
874 {
875         dump("pullarg");
876         MathArray a = array();
877
878         MathScriptInset const * p = par()->asScriptInset();
879         if (p) {
880                 // special handling for scripts
881                 const bool up = p->hasUp();
882                 popLeft();
883                 MathScriptInset * q = nextAtom()->asScriptInset();
884                 if (q)
885                         q->removeScript(up);
886                 ++pos();
887                 array().insert(pos(), a);
888                 return;
889         }
890
891         if (popLeft()) {
892                 plainErase();
893                 array().insert(pos(), a);
894                 if (goright) 
895                         pos() += a.size();
896         }
897 }
898
899
900 void MathCursor::normalize()
901 {
902         // rebreak
903         {
904                 MathIterator it = ibegin(formula()->par().nucleus());
905                 MathIterator et = iend(formula()->par().nucleus());
906                 for ( ; it != et; ++it) 
907                         if (it.par()->asBoxInset())
908                                 it.par()->asBoxInset()->rebreak();
909         }
910
911         if (idx() >= par()->nargs()) {
912                 lyxerr << "this should not really happen - 1: "
913                        << idx() << " " << par()->nargs() << "\n";
914                 dump("error 2");
915         }
916         idx() = min(idx(), par()->nargs() - 1);
917
918         if (pos() > size()) {
919                 lyxerr << "this should not really happen - 2: "
920                         << pos() << " " << size() <<  " in idx: " << idx()
921                         << " in atom: '";
922                 WriteStream wi(lyxerr, false);
923                 par()->write(wi);
924                 lyxerr << "\n";
925                 dump("error 4");
926         }
927         pos() = min(pos(), size());
928 }
929
930
931 MathCursor::size_type MathCursor::size() const
932 {
933         return array().size();
934 }
935
936
937 MathCursor::col_type MathCursor::hullCol() const
938 {
939         return Cursor_[0].par_->asGridInset()->col(Cursor_[0].idx_);
940 }
941
942
943 MathCursor::row_type MathCursor::hullRow() const
944 {
945         return Cursor_[0].par_->asGridInset()->row(Cursor_[0].idx_);
946 }
947
948
949 bool MathCursor::hasPrevAtom() const
950 {
951         return pos() > 0;
952 }
953
954
955 bool MathCursor::hasNextAtom() const
956 {
957         return pos() < size();
958 }
959
960
961 MathAtom const & MathCursor::prevAtom() const
962 {
963         lyx::Assert(pos() > 0);
964         return array().at(pos() - 1);
965 }
966
967
968 MathAtom & MathCursor::prevAtom()
969 {
970         lyx::Assert(pos() > 0);
971         return array().at(pos() - 1);
972 }
973
974
975 MathAtom const & MathCursor::nextAtom() const
976 {
977         lyx::Assert(pos() < size());
978         return array().at(pos());
979 }
980
981
982 MathAtom & MathCursor::nextAtom()
983 {
984         lyx::Assert(pos() < size());
985         return array().at(pos());
986 }
987
988
989 MathArray & MathCursor::array() const
990 {
991         static MathArray dummy;
992
993         if (idx() >= par()->nargs()) {
994                 lyxerr << "############  idx_ " << idx() << " not valid\n";
995                 return dummy;
996         }
997
998         if (Cursor_.size() == 0) {
999                 lyxerr << "############  Cursor_.size() == 0 not valid\n";
1000                 return dummy;
1001         }
1002
1003         return cursor().cell();
1004 }
1005
1006
1007 MathXArray & MathCursor::xarray() const
1008 {
1009         static MathXArray dummy;
1010
1011         if (Cursor_.size() == 0) {
1012                 lyxerr << "############  Cursor_.size() == 0 not valid\n";
1013                 return dummy;
1014         }
1015
1016         return cursor().xcell();
1017 }
1018
1019
1020 void MathCursor::idxNext()
1021 {
1022         par()->idxNext(idx(), pos());
1023 }
1024
1025
1026 void MathCursor::idxPrev()
1027 {
1028         par()->idxPrev(idx(), pos());
1029 }
1030
1031
1032 void MathCursor::splitCell()
1033 {
1034         if (idx() + 1 == par()->nargs()) 
1035                 return;
1036         MathArray ar = array();
1037         ar.erase(0, pos());
1038         array().erase(pos(), size());
1039         ++idx();
1040         pos() = 0;
1041         array().insert(0, ar);
1042 }
1043
1044
1045 void MathCursor::breakLine()
1046 {
1047         // leave inner cells
1048         while (popRight())
1049                 ;
1050
1051         MathHullInset * p = formula()->par()->asHullInset();
1052         if (!p)
1053                 return;
1054
1055         if (p->getType() == LM_OT_SIMPLE || p->getType() == LM_OT_EQUATION) {
1056                 p->mutate(LM_OT_EQNARRAY);
1057                 idx() = 0;
1058                 pos() = size();
1059         } else {
1060                 p->addRow(hullRow());
1061
1062                 // split line
1063                 const row_type r = hullRow();
1064                 for (col_type c = hullCol() + 1; c < p->ncols(); ++c)
1065                         p->cell(p->index(r, c)).swap(p->cell(p->index(r + 1, c)));
1066
1067                 // split cell
1068                 splitCell();
1069                 p->cell(idx()).swap(p->cell(idx() + p->ncols() - 1));
1070         }
1071 }
1072
1073
1074 //void MathCursor::readLine(MathArray & ar) const
1075 //{
1076 //      idx_type base = row() * par()->ncols();
1077 //      for (idx_type off = 0; off < par()->ncols(); ++off)
1078 //              ar.push_back(par()->cell(base + off));
1079 //}
1080
1081
1082 char MathCursor::valign() const
1083 {
1084         idx_type idx;
1085         MathGridInset * p = enclosingGrid(idx);
1086         return p ? p->valign() : '\0';
1087 }
1088
1089
1090 char MathCursor::halign() const
1091 {
1092         idx_type idx;
1093         MathGridInset * p = enclosingGrid(idx);
1094         return p ? p->halign(idx % p->ncols()) : '\0';
1095 }
1096
1097
1098 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1099 {
1100         MathCursorPos anc = normalAnchor();
1101         if (anc < cursor()) {
1102                 i1 = anc;
1103                 i2 = cursor();
1104         } else {
1105                 i1 = cursor();
1106                 i2 = anc;
1107         }
1108 }
1109
1110
1111 MathCursorPos & MathCursor::cursor()
1112 {
1113         lyx::Assert(Cursor_.size());
1114         return Cursor_.back();
1115 }
1116
1117
1118 MathCursorPos const & MathCursor::cursor() const
1119 {
1120         lyx::Assert(Cursor_.size());
1121         return Cursor_.back();
1122 }
1123
1124
1125 bool MathCursor::goUpDown(bool up)
1126 {
1127         int xlow, xhigh, ylow, yhigh;
1128
1129   int xo, yo;
1130         getPos(xo, yo);
1131
1132         // try current cell first
1133         xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1134         if (up)
1135                 yhigh = yo - 4;
1136         else
1137                 ylow = yo + 4;
1138         if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh))
1139                 return true;
1140
1141         // try to find an inset that knows better then we
1142         while (1) {
1143                 // we found a cell that think something "below" us.
1144                 if (up) {
1145                         if (par()->idxUp(idx()))
1146                                 break;
1147                 } else {
1148                         if (par()->idxDown(idx()))
1149                                 break;
1150                 }
1151
1152                 if (!popLeft()) {
1153                         // no such inset found, just take something "above"
1154                         return
1155                                 bruteFind(xo, yo,
1156                                         formula()->xlow(),
1157                                         formula()->xhigh(),
1158                                         up ? formula()->ylow() : yo + 4,
1159                                         up ? yo - 4 : formula()->yhigh()
1160                                 );
1161                 }
1162         }
1163         xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1164         bruteFind(xo, yo, xlow, xhigh, ylow, yhigh);
1165         return true;
1166 }
1167
1168
1169 bool MathCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1170 {
1171         cursor_type best_cursor;
1172         double best_dist = 1e10;
1173
1174         MathIterator it = ibegin(formula()->par().nucleus());
1175         MathIterator et = iend(formula()->par().nucleus());
1176         for ( ; it != et; ++it) {
1177                 // avoid invalid nesting hen selecting
1178                 if (selection_ && !positionable(it.cursor(), Anchor_))
1179                         continue;
1180                 int xo = it.position().xpos();
1181                 int yo = it.position().ypos();
1182                 if (xlow - 2 <= xo && xo <= xhigh + 2 &&
1183                     ylow - 2 <= yo && yo <= yhigh + 2)
1184                 {
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         latexkeys const * l = in_word_set(s.substr(1));
1270         if (l && (l->token == LM_TK_FONT || l->token == LM_TK_OLDFONT)) {
1271                 lastcode_ = static_cast<MathTextCodes>(l->id);
1272                 return true;
1273         }
1274
1275         niceInsert(createMathInset(s.substr(1)));
1276         return true;
1277 }
1278
1279
1280 bool MathCursor::script(bool up)
1281 {
1282         macroModeClose();
1283         selCut();
1284         if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1285                 prevAtom()->asScriptInset()->ensure(up);
1286                 pushRight(prevAtom());
1287                 idx() = up;
1288                 pos() = size();
1289         } else if (hasNextAtom() && nextAtom()->asScriptInset()) {
1290                 nextAtom()->asScriptInset()->ensure(up);
1291                 pushLeft(nextAtom());
1292                 idx() = up;
1293                 pos() = 0;
1294         } else {
1295                 plainInsert(MathAtom(new MathScriptInset(up)));
1296                 prevAtom()->asScriptInset()->ensure(up);
1297                 pushRight(prevAtom());
1298                 idx() = up;
1299                 pos() = 0;
1300         }
1301         selPaste();
1302         dump("1");
1303         return true;
1304 }
1305
1306
1307 bool MathCursor::interpret(char c)
1308 {
1309
1310         // Removed super/subscript handling from here  to ::script -MV
1311
1312         // handle macroMode
1313         if (inMacroMode()) {
1314                 string name = macroName();
1315
1316                 if (name == "\\" && c == '#') {
1317                         insert(c, LM_TC_TEX);
1318                         return true;
1319                 }
1320
1321                 if (name == "\\" && c == '\\') {
1322                         backspace();
1323                         interpret("\\backslash");
1324                         return true;
1325                 }
1326
1327                 if (name == "\\#" && '1' <= c && c <= '9') {
1328                         insert(c, LM_TC_TEX);
1329                         macroModeClose();
1330                         return true;
1331                 }
1332
1333                 if (isalpha(c)) {
1334                         insert(c, LM_TC_TEX);
1335                         return true;
1336                 }
1337
1338                 if (name == "\\") {
1339                         insert(c, LM_TC_TEX);
1340                         macroModeClose();
1341                         return true;
1342                 }
1343
1344                 macroModeClose();
1345                 return true;
1346         }
1347
1348         if (selection_) {
1349                 selClear();
1350                 if (c == ' ')
1351                         return true;
1352                 // fall through in the other cases
1353         }
1354
1355         if (lastcode_ == LM_TC_TEXTRM || par()->asBoxInset()) {
1356                 // suppress direct insertion of two spaces in a row
1357                 // the still allows typing  '<space>a<space>' and deleting the 'a', but
1358                 // it is better than nothing...
1359                 if (c == ' ' && hasPrevAtom() && prevAtom()->getChar() == ' ')
1360                         return true;
1361                 insert(c, LM_TC_TEXTRM);
1362                 return true;
1363         }
1364
1365         if (c == ' ') {
1366                 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1367                         prevAtom()->asSpaceInset()->incSpace();
1368                         return true;
1369                 }
1370                 if (popRight())
1371                         return true;
1372                 // if are at the very end, leave the formula
1373                 return pos() != size();
1374         }
1375
1376 /*
1377         if (strchr("{}", c)) {
1378                 insert(c, LM_TC_TEX);
1379                 return true;
1380         }
1381 */
1382
1383         if (c == '{') {
1384                 niceInsert(MathAtom(new MathBraceInset));
1385                 return true;
1386         }
1387
1388         if (c == '}') {
1389                 return true;
1390         }
1391
1392         if (strchr("#$%", c)) {
1393                 insert(MathAtom(new MathSpecialCharInset(c)));  
1394                 lastcode_ = LM_TC_VAR;
1395                 return true;
1396         }
1397
1398         if (isalpha(c) && lastcode_ == LM_TC_GREEK) {
1399                 insert(c, LM_TC_VAR);
1400                 return true;
1401         }
1402
1403         if (isalpha(c) && lastcode_ == LM_TC_GREEK1) {
1404                 insert(c, LM_TC_VAR);
1405                 lastcode_ = LM_TC_VAR;
1406                 return true;
1407         }
1408
1409         if (c == '\\') {
1410                 insert(c, LM_TC_TEX);
1411                 //bv->owner()->message(_("TeX mode"));
1412                 return true;    
1413         }
1414
1415         // no special circumstances, so insert the character without any fuss
1416         insert(c, lastcode_ == LM_TC_MIN ? MathCharInset::nativeCode(c) : lastcode_);
1417         lastcode_ = LM_TC_MIN;
1418         return true;
1419 }
1420
1421
1422
1423 MathCursorPos MathCursor::normalAnchor() const
1424 {
1425         if (Anchor_.size() < Cursor_.size()) {
1426                 Anchor_ = Cursor_;
1427                 lyxerr << "unusual Anchor size\n";
1428                 dump("1");
1429         }
1430         //lyx::Assert(Anchor_.size() >= Cursor_.size());
1431         // use Anchor on the same level as Cursor
1432         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1433         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1434                 // anchor is behind cursor -> move anchor behind the inset
1435                 ++normal.pos_;
1436         }
1437         return normal;
1438 }
1439
1440
1441 void MathCursor::stripFromLastEqualSign()
1442 {
1443         // find position of last '=' in the array
1444         MathArray & ar = cursor().cell();
1445         MathArray::const_iterator et = ar.end();
1446         for (MathArray::const_iterator it = ar.begin(); it != ar.end(); ++it)
1447                 if ((*it)->getChar() == '=')
1448                         et = it;
1449
1450         // delete everything behind this position
1451         ar.erase(et - ar.begin(), ar.size());
1452         pos() = ar.size(); 
1453 }
1454
1455
1456 void MathCursor::setSelection(cursor_type const & where, size_type n)
1457 {
1458         selection_ = true;
1459         Anchor_ = where;
1460         Cursor_ = where;
1461         cursor().pos_ += n;
1462 }