]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
merge MathArray and MathXArray classes.
[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 #include <lyxrc.h>
20
21 #ifdef __GNUG__
22 #pragma implementation
23 #endif
24
25 #include "support/lstrings.h"
26 #include "support/LAssert.h"
27 #include "BufferView.h"
28 #include "debug.h"
29 #include "LColor.h"
30 #include "frontends/Painter.h"
31 #include "math_cursor.h"
32 #include "formulabase.h"
33 #include "math_autocorrect.h"
34 #include "math_arrayinset.h"
35 #include "math_braceinset.h"
36 #include "math_casesinset.h"
37 #include "math_charinset.h"
38 #include "math_extern.h"
39 #include "math_factory.h"
40 #include "math_hullinset.h"
41 #include "math_iterator.h"
42 #include "math_macroarg.h"
43 #include "math_macrotemplate.h"
44 #include "math_mathmlstream.h"
45 #include "math_parser.h"
46 #include "math_replace.h"
47 #include "math_scriptinset.h"
48 #include "math_spaceinset.h"
49 #include "math_support.h"
50 #include "math_unknowninset.h"
51
52 #include <algorithm>
53 #include <cctype>
54
55 //#define FILEDEBUG 1
56
57 using std::endl;
58 using std::min;
59 using std::max;
60 using std::swap;
61 using std::vector;
62 using std::ostringstream;
63 using std::isalpha;
64
65
66 // matheds own cut buffer
67 MathGridInset theCutBuffer = MathGridInset(1, 1);
68
69
70 MathCursor::MathCursor(InsetFormulaBase * formula, bool front)
71         :       formula_(formula), autocorrect_(false), selection_(false)
72 {
73         front ? first() : last();
74         Anchor_ = Cursor_;
75 }
76
77
78 MathCursor::~MathCursor()
79 {
80   // ensure that 'notifyCursorLeave' is called
81   while (popLeft())
82     ;
83 }
84
85
86 void MathCursor::push(MathAtom & t)
87 {
88         Cursor_.push_back(MathCursorPos(t.nucleus()));
89 }
90
91
92 void MathCursor::pushLeft(MathAtom & t)
93 {
94         //cerr << "Entering atom "; t->write(cerr, false); cerr << " left\n";
95         push(t);
96         t->idxFirst(idx(), pos());
97 }
98
99
100 void MathCursor::pushRight(MathAtom & t)
101 {
102         //cerr << "Entering atom "; t->write(cerr, false); cerr << " right\n";
103         posLeft();
104         push(t);
105         t->idxLast(idx(), pos());
106 }
107
108
109 bool MathCursor::popLeft()
110 {
111         //cerr << "Leaving atom to the left\n";
112         if (depth() <= 1) {
113                 if (depth() == 1)
114                         par()->notifyCursorLeaves();
115                 return false;
116         }
117         par()->notifyCursorLeaves();
118         Cursor_.pop_back();
119         return true;
120 }
121
122
123 bool MathCursor::popRight()
124 {
125         //cerr << "Leaving atom "; par()->write(cerr, false); cerr << " right\n";
126         if (depth() <= 1) {
127                 if (depth() == 1)
128                         par()->notifyCursorLeaves();
129                 return false;
130         }
131         par()->notifyCursorLeaves();
132         Cursor_.pop_back();
133         posRight();
134         return true;
135 }
136
137
138
139 #if FILEDEBUG
140         void MathCursor::dump(char const * what) const
141         {
142                 lyxerr << "MC: " << what << "\n";
143                 lyxerr << " Cursor: " << depth() << "\n";
144                 for (unsigned i = 0; i < depth(); ++i)
145                         lyxerr << "    i: " << i << " " << Cursor_[i] << "\n";
146                 lyxerr << " Anchor: " << Anchor_.size() << "\n";
147                 for (unsigned i = 0; i < Anchor_.size(); ++i)
148                         lyxerr << "    i: " << i << " " << Anchor_[i] << "\n";
149                 lyxerr  << " sel: " << selection_ << "\n";
150         }
151 #else
152         void MathCursor::dump(char const *) const {}
153 #endif
154
155
156 bool MathCursor::isInside(MathInset const * p) const
157 {
158         for (unsigned i = 0; i < depth(); ++i)
159                 if (Cursor_[i].par_ == p)
160                         return true;
161         return false;
162 }
163
164
165 bool MathCursor::openable(MathAtom const & t, bool sel) const
166 {
167         if (!t->isActive())
168                 return false;
169
170         if (t->lock())
171                 return false;
172
173         if (sel) {
174                 // we can't move into anything new during selection
175                 if (depth() == Anchor_.size())
176                         return false;
177                 if (t.nucleus() != Anchor_[depth()].par_)
178                         return false;
179         }
180         return true;
181 }
182
183
184 bool MathCursor::inNucleus() const
185 {
186         return par()->asScriptInset() && idx() == 2;
187 }
188
189
190 bool MathCursor::posLeft()
191 {
192         if (pos() == 0)
193                 return false;
194         --pos();
195         return true;
196 }
197
198
199 bool MathCursor::posRight()
200 {
201         if (pos() == size())
202                 return false;
203         ++pos();
204         return true;
205 }
206
207
208 bool MathCursor::left(bool sel)
209 {
210         dump("Left 1");
211         autocorrect_ = false;
212         targetx_ = -1; // "no target"
213         if (inMacroMode()) {
214                 macroModeClose();
215                 return true;
216         }
217         selHandle(sel);
218
219         if (hasPrevAtom() && openable(prevAtom(), sel)) {
220                 pushRight(prevAtom());
221                 return true;
222         }
223
224         return posLeft() || idxLeft() || popLeft() || selection_;
225 }
226
227
228 bool MathCursor::right(bool sel)
229 {
230         dump("Right 1");
231         autocorrect_ = false;
232         targetx_ = -1; // "no target"
233         if (inMacroMode()) {
234                 macroModeClose();
235                 return true;
236         }
237         selHandle(sel);
238
239         if (hasNextAtom() && openable(nextAtom(), sel)) {
240                 pushLeft(nextAtom());
241                 return true;
242         }
243
244         return posRight() || idxRight() || popRight() || selection_;
245 }
246
247
248 void MathCursor::first()
249 {
250         Cursor_.clear();
251         push(formula_->par());
252         par()->idxFirst(idx(), pos());
253 }
254
255
256 void MathCursor::last()
257 {
258         Cursor_.clear();
259         push(formula_->par());
260         par()->idxLast(idx(), pos());
261 }
262
263
264 bool positionable(MathIterator const & cursor, MathIterator const & anchor)
265 {
266         // avoid deeper nested insets when selecting
267         if (cursor.size() > anchor.size())
268                 return false;
269
270         // anchor might be deeper, should have same path then
271         for (MathIterator::size_type i = 0; i < cursor.size(); ++i)
272                 if (cursor[i].par_ != anchor[i].par_)
273                         return false;
274
275         // position should be ok.
276         return true;
277 }
278
279
280 void MathCursor::setPos(int x, int y)
281 {
282         dump("setPos 1");
283         bool res = bruteFind(x, y,
284                 formula()->xlow(), formula()->xhigh(),
285                 formula()->ylow(), formula()->yhigh());
286         if (!res) {
287                 // this can happen on creation of "math-display"
288                 dump("setPos 1.5");
289                 first();
290         }
291         targetx_ = -1; // "no target"
292         dump("setPos 2");
293 }
294
295
296
297 bool MathCursor::home(bool sel)
298 {
299         dump("home 1");
300         autocorrect_ = false;
301         selHandle(sel);
302         macroModeClose();
303         if (!par()->idxHome(idx(), pos()))
304                 return popLeft();
305         dump("home 2");
306         targetx_ = -1; // "no target"
307         return true;
308 }
309
310
311 bool MathCursor::end(bool sel)
312 {
313         dump("end 1");
314         autocorrect_ = false;
315         selHandle(sel);
316         macroModeClose();
317         if (!par()->idxEnd(idx(), pos()))
318                 return popRight();
319         dump("end 2");
320         targetx_ = -1; // "no target"
321         return true;
322 }
323
324
325 void MathCursor::plainErase()
326 {
327         array().erase(pos());
328 }
329
330
331 void MathCursor::markInsert()
332 {
333         //lyxerr << "inserting mark\n";
334         array().insert(pos(), MathAtom(new MathCharInset(0)));
335 }
336
337
338 void MathCursor::markErase()
339 {
340         //lyxerr << "deleting mark\n";
341         array().erase(pos());
342 }
343
344
345 void MathCursor::plainInsert(MathAtom const & t)
346 {
347         dump("plainInsert");
348         array().insert(pos(), t);
349         ++pos();
350 }
351
352
353 void MathCursor::insert(string const & str)
354 {
355         //lyxerr << "inserting '" << str << "'\n";
356         selClearOrDel();
357         for (string::const_iterator it = str.begin(); it != str.end(); ++it)
358                 plainInsert(MathAtom(new MathCharInset(*it)));
359 }
360
361
362 void MathCursor::insert(char c)
363 {
364         //lyxerr << "inserting '" << c << "'\n";
365         selClearOrDel();
366         plainInsert(MathAtom(new MathCharInset(c)));
367 }
368
369
370 void MathCursor::insert(MathAtom const & t)
371 {
372         macroModeClose();
373         selClearOrDel();
374         plainInsert(t);
375 }
376
377
378 void MathCursor::niceInsert(MathAtom const & t)
379 {
380         macroModeClose();
381         MathGridInset safe = grabAndEraseSelection();
382         plainInsert(t);
383         // enter the new inset and move the contents of the selection if possible
384         if (t->isActive()) {
385                 posLeft();
386                 pushLeft(nextAtom());
387                 paste(safe);
388         }
389 }
390
391
392 void MathCursor::insert(MathArray const & ar)
393 {
394         macroModeClose();
395         if (selection_)
396                 eraseSelection();
397
398         array().insert(pos(), ar);
399         pos() += ar.size();
400 }
401
402
403 void MathCursor::paste(MathArray const & ar)
404 {
405         Anchor_ = Cursor_;
406         selection_ = true;
407         array().insert(pos(), ar);
408         pos() += ar.size();
409 }
410
411
412 void MathCursor::paste(MathGridInset const & data)
413 {
414         if (data.nargs() == 1) {
415                 // single cell/part of cell
416                 paste(data.cell(0));
417         } else {
418                 // multiple cells
419                 idx_type idx; // index of upper left cell
420                 MathGridInset * p = enclosingGrid(idx);
421                 col_type const numcols = min(data.ncols(), p->ncols() - p->col(idx));
422                 row_type const numrows = min(data.nrows(), p->nrows() - p->row(idx));
423                 for (row_type row = 0; row < numrows; ++row) {
424                         for (col_type col = 0; col < numcols; ++col) {
425                                 idx_type i = p->index(row + p->row(idx), col + p->col(idx));
426                                 p->cell(i).append(data.cell(data.index(row, col)));
427                         }
428                         // append the left over horizontal cells to the last column
429                         idx_type i = p->index(row + p->row(idx), p->ncols() - 1);
430                         for (MathInset::col_type col = numcols; col < data.ncols(); ++col)
431                                 p->cell(i).append(data.cell(data.index(row, col)));
432                 }
433                 // append the left over vertical cells to the last _cell_
434                 idx_type i = p->nargs() - 1;
435                 for (row_type row = numrows; row < data.nrows(); ++row)
436                         for (col_type col = 0; col < data.ncols(); ++col)
437                                 p->cell(i).append(data.cell(data.index(row, col)));
438         }
439 }
440
441
442 void MathCursor::backspace()
443 {
444         autocorrect_ = false;
445         if (pos() == 0) {
446                 pullArg();
447                 return;
448         }
449
450         if (selection_) {
451                 selDel();
452                 return;
453         }
454
455 /*
456         if (prevAtom()->asScriptInset()) {
457                 // simply enter nucleus
458                 left();
459                 return;
460         }
461
462         if (inNucleus()) {
463                 // we are in nucleus
464                 if (pos() == 1) {
465                 }
466         }
467 */
468
469         --pos();
470         plainErase();
471 }
472
473
474 void MathCursor::erase()
475 {
476         autocorrect_ = false;
477         if (inMacroMode())
478                 return;
479
480         if (selection_) {
481                 selDel();
482                 return;
483         }
484
485         // delete empty cells if possible
486         if (array().empty())
487                 if (par()->idxDelete(idx()))
488                         return;
489
490         // old behaviour when in last position of cell
491         if (pos() == size()) {
492                 par()->idxGlue(idx());
493                 return;
494         }
495
496 /*
497         // if we are standing in front of a script inset, grab item before us and
498         // move it into nucleus
499         // and remove first thing.
500         if (hasNextAtom() && nextAtom()->asScriptInset()) {
501                 if (hasPrevAtom()) {
502                         MathAtom at = prevAtom();
503                         --pos();
504                         array().erase(pos());
505                         pushLeft(nextAtom());
506                         if (array().empty())
507                                 array().push_back(at);
508                         else
509                                 array()[0] = at;
510                         pos() = 1;
511                 } else {
512                         pushLeft(nextAtom());
513                         array().clear();
514                 }
515                 return;
516         }
517 */
518
519         plainErase();
520 }
521
522
523 void MathCursor::delLine()
524 {
525         autocorrect_ = false;
526         macroModeClose();
527
528         if (selection_) {
529                 selDel();
530                 return;
531         }
532
533         if (par()->nrows() > 1) {
534                 // grid are the only things with more than one row...
535                 lyx::Assert(par()->asGridInset());
536                 par()->asGridInset()->delRow(hullRow());
537         }
538
539         if (idx() >= par()->nargs())
540                 idx() = par()->nargs() - 1;
541
542         if (pos() > size())
543                 pos() = size();
544 }
545
546
547 bool MathCursor::up(bool sel)
548 {
549         dump("up 1");
550         macroModeClose();
551         selHandle(sel);
552         MathIterator save = Cursor_;
553         if (goUpDown(true))
554                 return true;
555         Cursor_ = save;
556         autocorrect_ = false;
557         return selection_;
558 }
559
560
561 bool MathCursor::down(bool sel)
562 {
563         dump("down 1");
564         macroModeClose();
565         selHandle(sel);
566         MathIterator save = Cursor_;
567         if (goUpDown(false))
568                 return true;
569         Cursor_ = save;
570         autocorrect_ = false;
571         return selection_;
572 }
573
574
575 bool MathCursor::toggleLimits()
576 {
577         if (!hasNextAtom())
578                 return false;
579         MathScriptInset * t = nextAtom()->asScriptInset();
580         if (!t)
581                 return false;
582         int old = t->limits();
583         t->limits(old < 0 ? 1 : -1);
584         return old != t->limits();
585 }
586
587
588 void MathCursor::macroModeClose()
589 {
590         MathUnknownInset * p = inMacroMode();
591         if (!p)
592                 return;
593         p->finalize();
594         string s = p->name();
595         --pos();
596         array().erase(pos());
597         if (s != "\\")
598                 interpret(s);
599 }
600
601
602 string MathCursor::macroName() const
603 {
604         return inMacroMode() ? inMacroMode()->name() : string();
605 }
606
607
608 void MathCursor::selClear()
609 {
610         Anchor_.clear();
611         selection_ = false;
612 }
613
614
615 void MathCursor::selCopy()
616 {
617         dump("selCopy");
618         if (selection_) {
619                 theCutBuffer = grabSelection();
620                 selection_ = false;
621         } else {
622                 theCutBuffer = MathGridInset(1, 1);
623         }
624 }
625
626
627 void MathCursor::selCut()
628 {
629         dump("selCut");
630         theCutBuffer = grabAndEraseSelection();
631 }
632
633
634 void MathCursor::selDel()
635 {
636         dump("selDel");
637         if (selection_) {
638                 eraseSelection();
639                 selection_ = false;
640         }
641 }
642
643
644 void MathCursor::selPaste()
645 {
646         dump("selPaste");
647         selClearOrDel();
648         paste(theCutBuffer);
649         //grabSelection();
650         selection_ = false;
651 }
652
653
654 void MathCursor::selHandle(bool sel)
655 {
656         if (sel == selection_)
657                 return;
658         //clear();
659         Anchor_ = Cursor_;
660         selection_ = sel;
661 }
662
663
664 void MathCursor::selStart()
665 {
666         dump("selStart 1");
667         //clear();
668         Anchor_ = Cursor_;
669         selection_ = true;
670         dump("selStart 2");
671 }
672
673
674 void MathCursor::selClearOrDel()
675 {
676         if (lyxrc.auto_region_delete)
677                 selDel();
678         else
679                 selection_ = false;
680 }
681
682
683 void MathCursor::selGet(MathArray & ar)
684 {
685         dump("selGet");
686         if (selection_)
687                 ar = grabSelection().glue();
688 }
689
690
691
692 void MathCursor::drawSelection(MathPainterInfo & pi) const
693 {
694         if (!selection_)
695                 return;
696         MathCursorPos i1;
697         MathCursorPos i2;
698         getSelection(i1, i2);
699         i1.par_->drawSelection(pi, i1.idx_, i1.pos_, i2.idx_, i2.pos_);
700 }
701
702
703 void MathCursor::handleNest(MathAtom const & at)
704 {
705         at->cell(0) = grabAndEraseSelection().glue();
706         insert(at);
707         pushRight(prevAtom());
708 }
709
710
711 void MathCursor::getPos(int & x, int & y)
712 {
713         par()->getPos(idx(), pos(), x, y);
714 }
715
716
717 MathInset * MathCursor::par() const
718 {
719         return cursor().par_;
720 }
721
722
723 InsetFormulaBase * MathCursor::formula() const
724 {
725         return formula_;
726 }
727
728
729 MathCursor::idx_type MathCursor::idx() const
730 {
731         return cursor().idx_;
732 }
733
734
735 MathCursor::idx_type & MathCursor::idx()
736 {
737         return cursor().idx_;
738 }
739
740
741 MathCursor::pos_type MathCursor::pos() const
742 {
743         return cursor().pos_;
744 }
745
746
747 MathCursor::pos_type & MathCursor::pos()
748 {
749         return cursor().pos_;
750 }
751
752
753 MathUnknownInset * MathCursor::inMacroMode() const
754 {
755         if (!hasPrevAtom())
756                 return 0;
757         MathUnknownInset * p = prevAtom()->asUnknownInset();
758         return (p && !p->final()) ? p : 0;
759 }
760
761
762 bool MathCursor::inMacroArgMode() const
763 {
764         return pos() > 0 && prevAtom()->getChar() == '#';
765 }
766
767
768 bool MathCursor::selection() const
769 {
770         return selection_;
771 }
772
773
774 MathGridInset * MathCursor::enclosingGrid(MathCursor::idx_type & idx) const
775 {
776         for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
777                 MathGridInset * p = Cursor_[i].par_->asGridInset();
778                 if (p) {
779                         idx = Cursor_[i].idx_;
780                         return p;
781                 }
782         }
783         return 0;
784 }
785
786
787 MathHullInset * MathCursor::enclosingHull(MathCursor::idx_type & idx) const
788 {
789         for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
790                 MathHullInset * p = Cursor_[i].par_->asHullInset();
791                 if (p) {
792                         idx = Cursor_[i].idx_;
793                         return p;
794                 }
795         }
796         return 0;
797 }
798
799
800 void MathCursor::popToEnclosingGrid()
801 {
802         while (depth() && !Cursor_.back().par_->asGridInset())
803                 Cursor_.pop_back();
804 }
805
806
807 void MathCursor::popToEnclosingHull()
808 {
809         while (depth() && !Cursor_.back().par_->asHullInset())
810                 Cursor_.pop_back();
811 }
812
813
814 void MathCursor::pullArg()
815 {
816         dump("pullarg");
817         MathArray a = array();
818         if (popLeft()) {
819                 plainErase();
820                 array().insert(pos(), a);
821                 Anchor_ = Cursor_;
822         } else {
823                 formula()->mutateToText();
824         }
825 }
826
827
828 void MathCursor::touch()
829 {
830         MathIterator::const_iterator it = Cursor_.begin();
831         MathIterator::const_iterator et = Cursor_.end();
832         for ( ; it != et; ++it)
833                 it->cell().touch();
834 }
835
836
837 void MathCursor::normalize()
838 {
839         if (idx() >= par()->nargs()) {
840                 lyxerr << "this should not really happen - 1: "
841                        << idx() << " " << par()->nargs() << " in: " << par() << "\n";
842                 dump("error 2");
843         }
844         idx() = min(idx(), par()->nargs() - 1);
845
846         if (pos() > size()) {
847                 lyxerr << "this should not really happen - 2: "
848                         << pos() << " " << size() <<  " in idx: " << idx()
849                         << " in atom: '";
850                 WriteStream wi(lyxerr, false, true);
851                 par()->write(wi);
852                 lyxerr << "\n";
853                 dump("error 4");
854         }
855         pos() = min(pos(), size());
856
857         // remove empty scripts if possible
858         if (1) {
859                 for (pos_type i = 0; i < size(); ++i) {
860                         MathScriptInset * p = array()[i]->asScriptInset();
861                         if (p) {
862                                 p->removeEmptyScripts();
863                                 //if (p->empty())
864                                 //      array().erase(i);
865                         }
866                 }
867         }
868
869         // fix again position
870         pos() = min(pos(), size());
871 }
872
873
874 MathCursor::size_type MathCursor::size() const
875 {
876         return array().size();
877 }
878
879
880 MathCursor::col_type MathCursor::hullCol() const
881 {
882         idx_type idx = 0;
883         MathHullInset * p = enclosingHull(idx);
884         return p->col(idx);
885 }
886
887
888 MathCursor::row_type MathCursor::hullRow() const
889 {
890         idx_type idx = 0;
891         MathHullInset * p = enclosingHull(idx);
892         return p->row(idx);
893 }
894
895
896 bool MathCursor::hasPrevAtom() const
897 {
898         return pos() > 0;
899 }
900
901
902 bool MathCursor::hasNextAtom() const
903 {
904         return pos() < size();
905 }
906
907
908 MathAtom const & MathCursor::prevAtom() const
909 {
910         lyx::Assert(pos() > 0);
911         return array()[pos() - 1];
912 }
913
914
915 MathAtom & MathCursor::prevAtom()
916 {
917         lyx::Assert(pos() > 0);
918         return array()[pos() - 1];
919 }
920
921
922 MathAtom const & MathCursor::nextAtom() const
923 {
924         lyx::Assert(pos() < size());
925         return array()[pos()];
926 }
927
928
929 MathAtom & MathCursor::nextAtom()
930 {
931         lyx::Assert(pos() < size());
932         return array()[pos()];
933 }
934
935
936 MathArray & MathCursor::array() const
937 {
938         static MathArray dummy;
939
940         if (idx() >= par()->nargs()) {
941                 lyxerr << "############  idx_ " << idx() << " not valid\n";
942                 return dummy;
943         }
944
945         if (depth() == 0) {
946                 lyxerr << "############  depth() == 0 not valid\n";
947                 return dummy;
948         }
949
950         return cursor().cell();
951 }
952
953
954 void MathCursor::idxNext()
955 {
956         par()->idxNext(idx(), pos());
957 }
958
959
960 void MathCursor::idxPrev()
961 {
962         par()->idxPrev(idx(), pos());
963 }
964
965
966 void MathCursor::splitCell()
967 {
968         if (idx() + 1 == par()->nargs())
969                 return;
970         MathArray ar = array();
971         ar.erase(0, pos());
972         array().erase(pos(), size());
973         ++idx();
974         pos() = 0;
975         array().insert(0, ar);
976 }
977
978
979 void MathCursor::breakLine()
980 {
981         // leave inner cells
982         while (popRight())
983                 ;
984
985         idx_type dummy;
986         MathHullInset * p = enclosingHull(dummy);
987         if (!p)
988                 return;
989
990         if (p->getType() == "simple" || p->getType() == "equation") {
991                 p->mutate("eqnarray");
992                 idx() = 1;
993                 pos() = 0;
994         } else {
995                 p->addRow(hullRow());
996
997                 // split line
998                 const row_type r = hullRow();
999                 for (col_type c = hullCol() + 1; c < p->ncols(); ++c)
1000                         std::swap(p->cell(p->index(r, c)), p->cell(p->index(r + 1, c)));
1001
1002                 // split cell
1003                 splitCell();
1004                 std::swap(p->cell(idx()), p->cell(idx() + p->ncols() - 1));
1005         }
1006 }
1007
1008
1009 //void MathCursor::readLine(MathArray & ar) const
1010 //{
1011 //      idx_type base = row() * par()->ncols();
1012 //      for (idx_type off = 0; off < par()->ncols(); ++off)
1013 //              ar.push_back(par()->cell(base + off));
1014 //}
1015
1016
1017 char MathCursor::valign() const
1018 {
1019         idx_type idx;
1020         MathGridInset * p = enclosingGrid(idx);
1021         return p ? p->valign() : '\0';
1022 }
1023
1024
1025 char MathCursor::halign() const
1026 {
1027         idx_type idx;
1028         MathGridInset * p = enclosingGrid(idx);
1029         return p ? p->halign(idx % p->ncols()) : '\0';
1030 }
1031
1032
1033 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1034 {
1035         MathCursorPos anc = normalAnchor();
1036         if (anc < cursor()) {
1037                 i1 = anc;
1038                 i2 = cursor();
1039         } else {
1040                 i1 = cursor();
1041                 i2 = anc;
1042         }
1043 }
1044
1045
1046 MathCursorPos & MathCursor::cursor()
1047 {
1048         lyx::Assert(depth());
1049         return Cursor_.back();
1050 }
1051
1052
1053 MathCursorPos const & MathCursor::cursor() const
1054 {
1055         lyx::Assert(depth());
1056         return Cursor_.back();
1057 }
1058
1059
1060 bool MathCursor::goUpDown(bool up)
1061 {
1062         // Be warned: The 'logic' implemented in this function is highly fragile.
1063         // A distance of one pixel or a '<' vs '<=' _really_ matters.
1064         // So fiddle around with it only if you know what you are doing!
1065   int xo, yo;
1066         getPos(xo, yo);
1067
1068         // check if we had something else in mind, if not, this is the future goal
1069         if (targetx_ == -1)
1070                 targetx_ = xo;
1071         else
1072                 xo = targetx_;
1073
1074         // try neigbouring script insets
1075         // try left
1076         if (hasPrevAtom()) {
1077                 MathScriptInset * p = prevAtom()->asScriptInset();
1078                 if (p && p->has(up)) {
1079                         --pos();
1080                         push(nextAtom());
1081                         idx() = up; // the superscript has index 1
1082                         pos() = size();
1083                         ///lyxerr << "updown: handled by scriptinset to the left\n";
1084                         return true;
1085                 }
1086         }
1087
1088         // try right
1089         if (hasNextAtom()) {
1090                 MathScriptInset * p = nextAtom()->asScriptInset();
1091                 if (p && p->has(up)) {
1092                         push(nextAtom());
1093                         idx() = up;
1094                         pos() = 0;
1095                         ///lyxerr << "updown: handled by scriptinset to the right\n";
1096                         return true;
1097                 }
1098         }
1099
1100         // try current cell
1101         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1102         //if (up)
1103         //      yhigh = yo - 4;
1104         //else
1105         //      ylow = yo + 4;
1106         //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1107         //      lyxerr << "updown: handled by brute find in the same cell\n";
1108         //      return true;
1109         //}
1110
1111         // try to find an inset that knows better then we
1112         while (1) {
1113                 ///lyxerr << "updown: We are in " << *par() << " idx: " << idx() << '\n';
1114                 // ask inset first
1115                 if (par()->idxUpDown(idx(), pos(), up, targetx_))
1116                         return true;
1117
1118                 // no such inset found, just take something "above"
1119                 ///lyxerr << "updown: handled by strange case\n";
1120                 if (!popLeft())
1121                         return
1122                                 bruteFind(xo, yo,
1123                                         formula()->xlow(),
1124                                         formula()->xhigh(),
1125                                         up ? formula()->ylow() : yo + 4,
1126                                         up ? yo - 4 : formula()->yhigh()
1127                                 );
1128
1129                 // any improvement so far?
1130                 int xnew, ynew;
1131                 getPos(xnew, ynew);
1132                 if (up ? ynew < yo : ynew > yo)
1133                         return true;
1134         }
1135 }
1136
1137
1138 bool MathCursor::bruteFind
1139         (int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1140 {
1141         MathIterator best_cursor;
1142         double best_dist = 1e10;
1143
1144         MathIterator it = ibegin(formula()->par().nucleus());
1145         MathIterator et = iend(formula()->par().nucleus());
1146         while (1) {
1147                 // avoid invalid nesting when selecting
1148                 if (!selection_ || positionable(it, Anchor_)) {
1149                         int xo, yo;
1150                         it.back().getPos(xo, yo);
1151                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1152                                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1153                                 // '<=' in order to take the last possible position
1154                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1155                                 if (d <= best_dist) {
1156                                         best_dist   = d;
1157                                         best_cursor = it;
1158                                 }
1159                         }
1160                 }
1161
1162                 if (it == et)
1163                         break;
1164                 ++it;
1165         }
1166
1167         if (best_dist < 1e10)
1168                 Cursor_ = best_cursor;
1169         return best_dist < 1e10;
1170 }
1171
1172
1173 bool MathCursor::idxLineFirst()
1174 {
1175         idx() -= idx() % par()->ncols();
1176         pos() = 0;
1177         return true;
1178 }
1179
1180
1181 bool MathCursor::idxLineLast()
1182 {
1183         idx() -= idx() % par()->ncols();
1184         idx() += par()->ncols() - 1;
1185         pos() = size();
1186         return true;
1187 }
1188
1189 bool MathCursor::idxLeft()
1190 {
1191         return par()->idxLeft(idx(), pos());
1192 }
1193
1194
1195 bool MathCursor::idxRight()
1196 {
1197         return par()->idxRight(idx(), pos());
1198 }
1199
1200
1201 bool MathCursor::interpret(string const & s)
1202 {
1203         //lyxerr << "interpret 1: '" << s << "'\n";
1204         if (s.empty())
1205                 return true;
1206
1207         //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
1208         //owner_->getIntl()->getTransManager().TranslateAndInsert(s[0], lt);
1209         //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
1210
1211         if (s.size() >= 5 && s.substr(0, 5) == "cases") {
1212                 unsigned int n = 1;
1213                 istringstream is(s.substr(5).c_str());
1214                 is >> n;
1215                 n = max(1u, n);
1216                 niceInsert(MathAtom(new MathCasesInset(n)));
1217                 return true;
1218         }
1219
1220         if (s.size() >= 6 && s.substr(0, 6) == "matrix") {
1221                 unsigned int m = 1;
1222                 unsigned int n = 1;
1223                 string v_align;
1224                 string h_align;
1225                 istringstream is(s.substr(6).c_str());
1226                 is >> m >> n >> v_align >> h_align;
1227                 m = max(1u, m);
1228                 n = max(1u, n);
1229                 v_align += 'c';
1230                 niceInsert(MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
1231                 return true;
1232         }
1233
1234         if (s.size() >= 7 && s.substr(0, 7) == "replace") {
1235                 ReplaceData rep;
1236                 istringstream is(s.substr(7).c_str());
1237                 string from, to;
1238                 is >> from >> to;
1239                 mathed_parse_cell(rep.from, from);
1240                 mathed_parse_cell(rep.to, to);
1241                 lyxerr << "replacing '" << from << "' with '" << to << "'\n";
1242                 par()->replace(rep);
1243                 return true;
1244         }
1245
1246         string name = s.substr(1);
1247
1248         if (name == "over" || name == "choose" || name == "atop") {
1249                 MathAtom t(createMathInset(name));
1250                 t->asNestInset()->cell(0) = array();
1251                 array().clear();
1252                 pos() = 0;
1253                 niceInsert(t);
1254                 popRight();
1255                 left();
1256                 return true;
1257         }
1258
1259         // prevent entering of recursive macros
1260         if (formula()->lyxCode() == Inset::MATHMACRO_CODE
1261                 && formula()->getInsetName() == name)
1262         {
1263                 lyxerr << "can't enter recursive macro\n";
1264                 return true;
1265         }
1266
1267         niceInsert(createMathInset(name));
1268         return true;
1269 }
1270
1271
1272 bool MathCursor::script(bool up)
1273 {
1274         // Hack to get \\^ and \\_ working
1275         if (inMacroMode() && macroName() == "\\") {
1276                 if (up)
1277                         interpret("\\mathcircumflex");
1278                 else
1279                         interpret('_');
1280                 return true;
1281         }
1282
1283         macroModeClose();
1284         MathGridInset safe = grabAndEraseSelection();
1285         if (inNucleus()) {
1286                 // we are in a nucleus of a script inset, move to _our_ script
1287                 par()->asScriptInset()->ensure(up);
1288                 idx() = up;
1289                 pos() = 0;
1290         } else if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1291                 prevAtom()->asScriptInset()->ensure(up);
1292                 pushRight(prevAtom());
1293                 idx() = up;
1294                 pos() = size();
1295         } else if (hasPrevAtom()) {
1296                 --pos();
1297                 array()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1298                 pushLeft(nextAtom());
1299                 idx() = up;
1300                 pos() = 0;
1301         } else {
1302                 plainInsert(MathAtom(new MathScriptInset(up)));
1303                 prevAtom()->asScriptInset()->ensure(up);
1304                 pushRight(prevAtom());
1305                 idx() = up;
1306                 pos() = 0;
1307         }
1308         paste(safe);
1309         dump("1");
1310         return true;
1311 }
1312
1313
1314 bool MathCursor::interpret(char c)
1315 {
1316         //lyxerr << "interpret 2: '" << c << "'\n";
1317         targetx_ = -1; // "no target"
1318         if (inMacroArgMode()) {
1319                 --pos();
1320                 plainErase();
1321                 int n = c - '0';
1322                 MathMacroTemplate * p = formula()->par()->asMacroTemplate();
1323                 if (p && 1 <= n && n <= p->numargs())
1324                         insert(MathAtom(new MathMacroArgument(c - '0')));
1325                 else {
1326                         insert(createMathInset("#"));
1327                         interpret(c); // try again
1328                 }
1329                 return true;
1330         }
1331
1332         // handle macroMode
1333         if (inMacroMode()) {
1334                 string name = macroName();
1335                 //lyxerr << "interpret name: '" << name << "'\n";
1336
1337                 if (name.empty() && c == '\\') {
1338                         backspace();
1339                         interpret("\\backslash");
1340                         return true;
1341                 }
1342
1343                 if (isalpha(c)) {
1344                         inMacroMode()->name() += c;
1345                         return true;
1346                 }
1347
1348                 // handle 'special char' macros
1349                 if (name == "\\") {
1350                         // remove the '\\'
1351                         backspace();
1352                         if (c == '\\')
1353                                 interpret("\\backslash");
1354                         else
1355                                 interpret(string("\\") + c);
1356                         return true;
1357                 }
1358
1359                 // leave macro mode and try again if necessary
1360                 macroModeClose();
1361                 if (c != ' ')
1362                         interpret(c);
1363                 return true;
1364         }
1365
1366         // This is annoying as one has to press <space> far too often.
1367         // Disable it.
1368
1369         if (0) {
1370                 // leave autocorrect mode if necessary
1371                 if (autocorrect_ && c == ' ') {
1372                         autocorrect_ = false;
1373                         return true;
1374                 }
1375         }
1376
1377         // just clear selection on pressing the space bar
1378         if (selection_ && c == ' ') {
1379                 selection_ = false;
1380                 return true;
1381         }
1382
1383         selClearOrDel();
1384
1385         if (c == '\\') {
1386                 //lyxerr << "starting with macro\n";
1387                 insert(MathAtom(new MathUnknownInset("\\", false)));
1388                 return true;
1389         }
1390
1391         if (c == '\n') {
1392                 if (currentMode() == MathInset::TEXT_MODE) 
1393                         insert(c);
1394                 return true;
1395         }
1396
1397         if (c == ' ') {
1398                 if (currentMode() == MathInset::TEXT_MODE) {
1399                         // insert spaces in text mode,
1400                         // but suppress direct insertion of two spaces in a row
1401                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1402                         // it is better than nothing...
1403                         if (!hasPrevAtom() || prevAtom()->getChar() != ' ')
1404                                 insert(c);
1405                         return true;
1406                 }
1407                 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1408                         prevAtom()->asSpaceInset()->incSpace();
1409                         return true;
1410                 }
1411                 if (popRight())
1412                         return true;
1413                 // if are at the very end, leave the formula
1414                 return pos() != size();
1415         }
1416
1417         if (c == '#') {
1418                 insert(c); // LM_TC_TEX;
1419                 return true;
1420         }
1421
1422 /*
1423         if (c == '{' || c == '}', c)) {
1424                 insert(c); // LM_TC_TEX;
1425                 return true;
1426         }
1427 */
1428
1429         if (c == '{') {
1430                 niceInsert(MathAtom(new MathBraceInset));
1431                 return true;
1432         }
1433
1434         if (c == '}') {
1435                 return true;
1436         }
1437
1438         if (c == '$') {
1439                 insert(createMathInset("$"));
1440                 return true;
1441         }
1442
1443         if (c == '%') {
1444                 insert(createMathInset("%"));
1445                 return true;
1446         }
1447
1448 /*
1449         if (isalpha(c) && lastcode_ == LM_TC_GREEK) {
1450                 insert(c, LM_TC_VAR);
1451                 return true;
1452         }
1453
1454         if (isalpha(c) && lastcode_ == LM_TC_GREEK1) {
1455                 insert(c, LM_TC_VAR);
1456                 lastcode_ = LM_TC_VAR;
1457                 return true;
1458         }
1459
1460         if (c == '\\') {
1461                 insert(c, LM_TC_TEX);
1462                 //bv->owner()->message(_("TeX mode"));
1463                 return true;
1464         }
1465 */
1466
1467         // try auto-correction
1468         //if (autocorrect_ && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1469         //      return true;
1470
1471         // no special circumstances, so insert the character without any fuss
1472         insert(c);
1473         autocorrect_ = true;
1474         return true;
1475 }
1476
1477
1478 void MathCursor::setSelection(MathIterator const & where, size_type n)
1479 {
1480         selection_ = true;
1481         Anchor_ = where;
1482         Cursor_ = where;
1483         cursor().pos_ += n;
1484 }
1485
1486
1487 void MathCursor::insetToggle()
1488 {
1489         if (hasNextAtom()) {
1490                 // toggle previous inset ...
1491                 nextAtom()->lock(!nextAtom()->lock());
1492         } else if (popLeft() && hasNextAtom()) {
1493                 // ... or enclosing inset if we are in the last inset position
1494                 nextAtom()->lock(!nextAtom()->lock());
1495                 posRight();
1496         }
1497 }
1498
1499
1500 string MathCursor::info() const
1501 {
1502         ostringstream os;
1503         os << "Math editor mode.  ";
1504         for (int i = 0, n = depth(); i < n; ++i) {
1505                 Cursor_[i].par_->infoize(os);
1506                 os << "  ";
1507         }
1508         if (hasPrevAtom())
1509                 if (prevAtom()->asSymbolInset() || prevAtom()->asScriptInset())
1510                         prevAtom()->infoize(os);
1511         os << "                    ";
1512         return os.str().c_str(); // .c_str() needed for lyxstring
1513 }
1514
1515
1516 unsigned MathCursor::depth() const
1517 {
1518         return Cursor_.size();
1519 }
1520
1521
1522
1523
1524 namespace {
1525
1526 void region(MathCursorPos const & i1, MathCursorPos const & i2,
1527         MathInset::row_type & r1, MathInset::row_type & r2,
1528         MathInset::col_type & c1, MathInset::col_type & c2)
1529 {
1530         MathInset * p = i1.par_;
1531         c1 = p->col(i1.idx_);
1532         c2 = p->col(i2.idx_);
1533         if (c1 > c2)
1534                 swap(c1, c2);
1535         r1 = p->row(i1.idx_);
1536         r2 = p->row(i2.idx_);
1537         if (r1 > r2)
1538                 swap(r1, r2);
1539 }
1540
1541 }
1542
1543
1544 MathGridInset MathCursor::grabSelection() const
1545 {
1546         if (!selection_)
1547                 return MathGridInset();
1548         MathCursorPos i1;
1549         MathCursorPos i2;
1550         getSelection(i1, i2);
1551         // shouldn't we assert on i1.par_ == i2.par_?
1552         if (i1.idx_ == i2.idx_) {
1553                 MathGridInset data(1, 1);
1554                 MathArray::const_iterator it = i1.cell().begin();
1555                 data.cell(0) = MathArray(it + i1.pos_, it + i2.pos_);
1556                 return data;
1557         }
1558         row_type r1, r2;
1559         col_type c1, c2;
1560         region(i1, i2, r1, r2, c1, c2);
1561         MathGridInset data(c2 - c1 + 1, r2 - r1 + 1);
1562         for (row_type row = 0; row < data.nrows(); ++row)
1563                 for (col_type col = 0; col < data.ncols(); ++col) {
1564                         idx_type i = i1.par_->index(row + r1, col + c1);
1565                         data.cell(data.index(row, col)) = i1.par_->cell(i);
1566                 }
1567         return data;
1568 }
1569
1570
1571 void MathCursor::eraseSelection()
1572 {
1573         MathCursorPos i1;
1574         MathCursorPos i2;
1575         getSelection(i1, i2);
1576         if (i1.idx_ == i2.idx_)
1577                 i1.cell().erase(i1.pos_, i2.pos_);
1578         else {
1579                 MathInset * p = i1.par_;
1580                 row_type r1, r2;
1581                 col_type c1, c2;
1582                 region(i1, i2, r1, r2, c1, c2);
1583                 for (row_type row = r1; row <= r2; ++row)
1584                         for (col_type col = c1; col <= c2; ++col)
1585                                 p->cell(p->index(row, col)).clear();
1586         }
1587         cursor() = i1;
1588 }
1589
1590
1591 MathGridInset MathCursor::grabAndEraseSelection()
1592 {
1593         if (!selection_)
1594                 return MathGridInset();
1595         MathGridInset res = grabSelection();
1596         eraseSelection();
1597         selection_ = false;
1598         return res;
1599 }
1600
1601
1602 MathCursorPos MathCursor::normalAnchor() const
1603 {
1604         if (Anchor_.size() < depth()) {
1605                 Anchor_ = Cursor_;
1606                 lyxerr << "unusual Anchor size\n";
1607         }
1608         //lyx::Assert(Anchor_.size() >= cursor.depth());
1609         // use Anchor on the same level as Cursor
1610         MathCursorPos normal = Anchor_[depth() - 1];
1611         if (depth() < Anchor_.size() && !(normal < cursor())) {
1612                 // anchor is behind cursor -> move anchor behind the inset
1613                 ++normal.pos_;
1614         }
1615         return normal;
1616 }
1617
1618
1619
1620 void MathCursor::handleExtern(const string & arg)
1621 {
1622         string lang;
1623         string extra;
1624         istringstream iss(arg.c_str());
1625         iss >> lang >> extra;
1626         if (extra.empty())
1627                 extra = "noextra";
1628
1629
1630         if (selection()) {
1631                 MathArray ar;
1632                 selGet(ar);
1633                 lyxerr << "use selection: " << ar << "\n";
1634                 insert(pipeThroughExtern(lang, extra, ar));
1635                 return;
1636         }
1637
1638         MathArray eq;
1639         eq.push_back(MathAtom(new MathCharInset('=')));
1640
1641         popToEnclosingHull();
1642
1643         idx_type idx = 0;
1644         MathHullInset * hull = enclosingHull(idx);
1645         lyx::Assert(hull);
1646         idxLineFirst();
1647
1648         if (hull->getType() == "simple") {
1649                 MathArray::size_type pos = cursor().cell().find_last(eq);
1650                 MathArray ar;
1651                 if (pos == size()) {
1652                         ar = array();
1653                         lyxerr << "use whole cell: " << ar << "\n";
1654                 } else {
1655                         ar = MathArray(array().begin() + pos + 1, array().end());
1656                         lyxerr << "use partial cell form pos: " << pos << "\n";
1657                 }
1658                 end();
1659                 insert(eq);
1660                 insert(pipeThroughExtern(lang, extra, ar));
1661                 return;
1662         }
1663
1664         if (hull->getType() == "equation") {
1665                 lyxerr << "use equation inset\n";
1666                 hull->mutate("eqnarray");
1667                 MathArray & ar = cursor().cell();
1668                 lyxerr << "use cell: " << ar << "\n";
1669                 idxRight();
1670                 cursor().cell() = eq;
1671                 idxRight();
1672                 cursor().cell() = pipeThroughExtern(lang, extra, ar);
1673                 idxLineLast();
1674                 return;
1675         }
1676
1677         {
1678                 lyxerr << "use eqnarray\n";
1679                 idxLineLast();
1680                 MathArray ar = cursor().cell();
1681                 lyxerr << "use cell: " << ar << "\n";
1682                 breakLine();
1683                 idxRight();
1684                 cursor().cell() = eq;
1685                 idxRight();
1686                 cursor().cell() = pipeThroughExtern(lang, extra, ar);
1687                 idxLineLast();
1688         }
1689
1690 }
1691
1692
1693 int MathCursor::dispatch(string const & cmd)
1694 {
1695         // try to dispatch to adajcent items if they are not editable
1696         // actually, this should only happen for mouse clicks...
1697         if (hasNextAtom() && !openable(nextAtom(), false))
1698                 if (int res = nextAtom()->dispatch(cmd, 0, 0))
1699                         return res;
1700         if (hasPrevAtom() && !openable(prevAtom(), false))
1701                 if (int res = prevAtom()->dispatch(cmd, 0, 0))
1702                         return res;
1703
1704         for (int i = Cursor_.size() - 1; i >= 0; --i) {
1705                 MathCursorPos & pos = Cursor_[i];
1706                 if (int res = pos.par_->dispatch(cmd, pos.idx_, pos.pos_))
1707                         return res;
1708         }
1709         return 0;
1710 }
1711
1712
1713 MathInset::mode_type MathCursor::currentMode() const
1714 {
1715         for (int i = Cursor_.size() - 1; i >= 0; --i) {
1716                 MathInset::mode_type res = Cursor_[i].par_->currentMode();
1717                 if (res != MathInset::UNDECIDED_MODE)
1718                         return res;
1719         }
1720         return MathInset::UNDECIDED_MODE;
1721 }
1722
1723
1724 void releaseMathCursor(BufferView * bv)
1725 {
1726         if (!mathcursor)
1727                 return;
1728         mathcursor->formula()->hideInsetCursor(bv);
1729         delete mathcursor;
1730         mathcursor = 0;
1731 }