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