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