]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
a bit more const correctness
[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 const * 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 void MathCursor::drawSelection(MathPainterInfo & pi) const
692 {
693         if (!selection_)
694                 return;
695         MathCursorPos i1;
696         MathCursorPos i2;
697         getSelection(i1, i2);
698         i1.par_->drawSelection(pi, i1.idx_, i1.pos_, i2.idx_, i2.pos_);
699 }
700
701
702 void MathCursor::handleNest(MathAtom const & at)
703 {
704 #ifdef WITH_WARNINGS
705 #warning temporarily disabled
706         //at->cell(0) = grabAndEraseSelection().glue();
707 #endif
708         insert(at);
709         pushRight(prevAtom());
710 }
711
712
713 void MathCursor::getPos(int & x, int & y)
714 {
715         par()->getPos(idx(), pos(), x, y);
716 }
717
718
719 MathInset * MathCursor::par() const
720 {
721         return cursor().par_;
722 }
723
724
725 InsetFormulaBase * MathCursor::formula() const
726 {
727         return formula_;
728 }
729
730
731 MathCursor::idx_type MathCursor::idx() const
732 {
733         return cursor().idx_;
734 }
735
736
737 MathCursor::idx_type & MathCursor::idx()
738 {
739         return cursor().idx_;
740 }
741
742
743 MathCursor::pos_type MathCursor::pos() const
744 {
745         return cursor().pos_;
746 }
747
748
749 MathCursor::pos_type & MathCursor::pos()
750 {
751         return cursor().pos_;
752 }
753
754
755 MathUnknownInset const * MathCursor::inMacroMode() const
756 {
757         if (!hasPrevAtom())
758                 return 0;
759         MathUnknownInset const * p = prevAtom()->asUnknownInset();
760         return (p && !p->final()) ? p : 0;
761 }
762
763
764 bool MathCursor::inMacroArgMode() const
765 {
766         return pos() > 0 && prevAtom()->getChar() == '#';
767 }
768
769
770 bool MathCursor::selection() const
771 {
772         return selection_;
773 }
774
775
776 MathGridInset * MathCursor::enclosingGrid(MathCursor::idx_type & idx) const
777 {
778         for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
779                 MathGridInset * p = Cursor_[i].par_->asGridInset();
780                 if (p) {
781                         idx = Cursor_[i].idx_;
782                         return p;
783                 }
784         }
785         return 0;
786 }
787
788
789 MathHullInset * MathCursor::enclosingHull(MathCursor::idx_type & idx) const
790 {
791         for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
792                 MathHullInset * p = Cursor_[i].par_->asHullInset();
793                 if (p) {
794                         idx = Cursor_[i].idx_;
795                         return p;
796                 }
797         }
798         return 0;
799 }
800
801
802 void MathCursor::popToEnclosingGrid()
803 {
804         while (depth() && !Cursor_.back().par_->asGridInset())
805                 Cursor_.pop_back();
806 }
807
808
809 void MathCursor::popToEnclosingHull()
810 {
811         while (depth() && !Cursor_.back().par_->asHullInset())
812                 Cursor_.pop_back();
813 }
814
815
816 void MathCursor::pullArg()
817 {
818         dump("pullarg");
819         MathArray a = array();
820         if (popLeft()) {
821                 plainErase();
822                 array().insert(pos(), a);
823                 Anchor_ = Cursor_;
824         } else {
825                 formula()->mutateToText();
826         }
827 }
828
829
830 void MathCursor::touch()
831 {
832         MathIterator::const_iterator it = Cursor_.begin();
833         MathIterator::const_iterator et = Cursor_.end();
834         for ( ; it != et; ++it)
835                 it->cell().touch();
836 }
837
838
839 void MathCursor::normalize()
840 {
841         if (idx() >= par()->nargs()) {
842                 lyxerr << "this should not really happen - 1: "
843                        << idx() << " " << par()->nargs() << " in: " << par() << "\n";
844                 dump("error 2");
845         }
846         idx() = min(idx(), par()->nargs() - 1);
847
848         if (pos() > size()) {
849                 lyxerr << "this should not really happen - 2: "
850                         << pos() << " " << size() <<  " in idx: " << idx()
851                         << " in atom: '";
852                 WriteStream wi(lyxerr, false, true);
853                 par()->write(wi);
854                 lyxerr << "\n";
855                 dump("error 4");
856         }
857         pos() = min(pos(), size());
858
859         // remove empty scripts if possible
860         if (1) {
861                 for (pos_type i = 0; i < size(); ++i) {
862                         MathScriptInset * p = array()[i]->asScriptInset();
863                         if (p) {
864                                 p->removeEmptyScripts();
865                                 //if (p->empty())
866                                 //      array().erase(i);
867                         }
868                 }
869         }
870
871         // fix again position
872         pos() = min(pos(), size());
873 }
874
875
876 MathCursor::size_type MathCursor::size() const
877 {
878         return array().size();
879 }
880
881
882 MathCursor::col_type MathCursor::hullCol() const
883 {
884         idx_type idx = 0;
885         MathHullInset * p = enclosingHull(idx);
886         return p->col(idx);
887 }
888
889
890 MathCursor::row_type MathCursor::hullRow() const
891 {
892         idx_type idx = 0;
893         MathHullInset * p = enclosingHull(idx);
894         return p->row(idx);
895 }
896
897
898 bool MathCursor::hasPrevAtom() const
899 {
900         return pos() > 0;
901 }
902
903
904 bool MathCursor::hasNextAtom() const
905 {
906         return pos() < size();
907 }
908
909
910 MathAtom const & MathCursor::prevAtom() const
911 {
912         lyx::Assert(pos() > 0);
913         return array()[pos() - 1];
914 }
915
916
917 MathAtom & MathCursor::prevAtom()
918 {
919         lyx::Assert(pos() > 0);
920         return array()[pos() - 1];
921 }
922
923
924 MathAtom const & MathCursor::nextAtom() const
925 {
926         lyx::Assert(pos() < size());
927         return array()[pos()];
928 }
929
930
931 MathAtom & MathCursor::nextAtom()
932 {
933         lyx::Assert(pos() < size());
934         return array()[pos()];
935 }
936
937
938 MathArray & MathCursor::array() const
939 {
940         static MathArray dummy;
941
942         if (idx() >= par()->nargs()) {
943                 lyxerr << "############  idx_ " << idx() << " not valid\n";
944                 return dummy;
945         }
946
947         if (depth() == 0) {
948                 lyxerr << "############  depth() == 0 not valid\n";
949                 return dummy;
950         }
951
952         return cursor().cell();
953 }
954
955
956 void MathCursor::idxNext()
957 {
958         par()->idxNext(idx(), pos());
959 }
960
961
962 void MathCursor::idxPrev()
963 {
964         par()->idxPrev(idx(), pos());
965 }
966
967
968 void MathCursor::splitCell()
969 {
970         if (idx() + 1 == par()->nargs())
971                 return;
972         MathArray ar = array();
973         ar.erase(0, pos());
974         array().erase(pos(), size());
975         ++idx();
976         pos() = 0;
977         array().insert(0, ar);
978 }
979
980
981 void MathCursor::breakLine()
982 {
983         // leave inner cells
984         while (popRight())
985                 ;
986
987         idx_type dummy;
988         MathHullInset * p = enclosingHull(dummy);
989         if (!p)
990                 return;
991
992         if (p->getType() == "simple" || p->getType() == "equation") {
993                 p->mutate("eqnarray");
994                 idx() = 1;
995                 pos() = 0;
996         } else {
997                 p->addRow(hullRow());
998
999                 // split line
1000                 const row_type r = hullRow();
1001                 for (col_type c = hullCol() + 1; c < p->ncols(); ++c)
1002                         std::swap(p->cell(p->index(r, c)), p->cell(p->index(r + 1, c)));
1003
1004                 // split cell
1005                 splitCell();
1006                 std::swap(p->cell(idx()), p->cell(idx() + p->ncols() - 1));
1007         }
1008 }
1009
1010
1011 //void MathCursor::readLine(MathArray & ar) const
1012 //{
1013 //      idx_type base = row() * par()->ncols();
1014 //      for (idx_type off = 0; off < par()->ncols(); ++off)
1015 //              ar.push_back(par()->cell(base + off));
1016 //}
1017
1018
1019 char MathCursor::valign() const
1020 {
1021         idx_type idx;
1022         MathGridInset * p = enclosingGrid(idx);
1023         return p ? p->valign() : '\0';
1024 }
1025
1026
1027 char MathCursor::halign() const
1028 {
1029         idx_type idx;
1030         MathGridInset * p = enclosingGrid(idx);
1031         return p ? p->halign(idx % p->ncols()) : '\0';
1032 }
1033
1034
1035 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1036 {
1037         MathCursorPos anc = normalAnchor();
1038         if (anc < cursor()) {
1039                 i1 = anc;
1040                 i2 = cursor();
1041         } else {
1042                 i1 = cursor();
1043                 i2 = anc;
1044         }
1045 }
1046
1047
1048 MathCursorPos & MathCursor::cursor()
1049 {
1050         lyx::Assert(depth());
1051         return Cursor_.back();
1052 }
1053
1054
1055 MathCursorPos const & MathCursor::cursor() const
1056 {
1057         lyx::Assert(depth());
1058         return Cursor_.back();
1059 }
1060
1061
1062 bool MathCursor::goUpDown(bool up)
1063 {
1064         // Be warned: The 'logic' implemented in this function is highly fragile.
1065         // A distance of one pixel or a '<' vs '<=' _really_ matters.
1066         // So fiddle around with it only if you know what you are doing!
1067   int xo, yo;
1068         getPos(xo, yo);
1069
1070         // check if we had something else in mind, if not, this is the future goal
1071         if (targetx_ == -1)
1072                 targetx_ = xo;
1073         else
1074                 xo = targetx_;
1075
1076         // try neigbouring script insets
1077         // try left
1078         if (hasPrevAtom()) {
1079                 MathScriptInset * p = prevAtom()->asScriptInset();
1080                 if (p && p->has(up)) {
1081                         --pos();
1082                         push(nextAtom());
1083                         idx() = up; // the superscript has index 1
1084                         pos() = size();
1085                         ///lyxerr << "updown: handled by scriptinset to the left\n";
1086                         return true;
1087                 }
1088         }
1089
1090         // try right
1091         if (hasNextAtom()) {
1092                 MathScriptInset * p = nextAtom()->asScriptInset();
1093                 if (p && p->has(up)) {
1094                         push(nextAtom());
1095                         idx() = up;
1096                         pos() = 0;
1097                         ///lyxerr << "updown: handled by scriptinset to the right\n";
1098                         return true;
1099                 }
1100         }
1101
1102         // try current cell
1103         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1104         //if (up)
1105         //      yhigh = yo - 4;
1106         //else
1107         //      ylow = yo + 4;
1108         //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1109         //      lyxerr << "updown: handled by brute find in the same cell\n";
1110         //      return true;
1111         //}
1112
1113         // try to find an inset that knows better then we
1114         while (1) {
1115                 ///lyxerr << "updown: We are in " << *par() << " idx: " << idx() << '\n';
1116                 // ask inset first
1117                 if (par()->idxUpDown(idx(), pos(), up, targetx_))
1118                         return true;
1119
1120                 // no such inset found, just take something "above"
1121                 ///lyxerr << "updown: handled by strange case\n";
1122                 if (!popLeft())
1123                         return
1124                                 bruteFind(xo, yo,
1125                                         formula()->xlow(),
1126                                         formula()->xhigh(),
1127                                         up ? formula()->ylow() : yo + 4,
1128                                         up ? yo - 4 : formula()->yhigh()
1129                                 );
1130
1131                 // any improvement so far?
1132                 int xnew, ynew;
1133                 getPos(xnew, ynew);
1134                 if (up ? ynew < yo : ynew > yo)
1135                         return true;
1136         }
1137 }
1138
1139
1140 bool MathCursor::bruteFind
1141         (int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1142 {
1143         MathIterator best_cursor;
1144         double best_dist = 1e10;
1145
1146         MathIterator it = ibegin(formula()->par().nucleus());
1147         MathIterator et = iend(formula()->par().nucleus());
1148         while (1) {
1149                 // avoid invalid nesting when selecting
1150                 if (!selection_ || positionable(it, Anchor_)) {
1151                         int xo, yo;
1152                         it.back().getPos(xo, yo);
1153                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1154                                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1155                                 // '<=' in order to take the last possible position
1156                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1157                                 if (d <= best_dist) {
1158                                         best_dist   = d;
1159                                         best_cursor = it;
1160                                 }
1161                         }
1162                 }
1163
1164                 if (it == et)
1165                         break;
1166                 ++it;
1167         }
1168
1169         if (best_dist < 1e10)
1170                 Cursor_ = best_cursor;
1171         return best_dist < 1e10;
1172 }
1173
1174
1175 bool MathCursor::idxLineFirst()
1176 {
1177         idx() -= idx() % par()->ncols();
1178         pos() = 0;
1179         return true;
1180 }
1181
1182
1183 bool MathCursor::idxLineLast()
1184 {
1185         idx() -= idx() % par()->ncols();
1186         idx() += par()->ncols() - 1;
1187         pos() = size();
1188         return true;
1189 }
1190
1191 bool MathCursor::idxLeft()
1192 {
1193         return par()->idxLeft(idx(), pos());
1194 }
1195
1196
1197 bool MathCursor::idxRight()
1198 {
1199         return par()->idxRight(idx(), pos());
1200 }
1201
1202
1203 bool MathCursor::interpret(string const & s)
1204 {
1205         //lyxerr << "interpret 1: '" << s << "'\n";
1206         if (s.empty())
1207                 return true;
1208
1209         //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
1210         //owner_->getIntl()->getTransManager().TranslateAndInsert(s[0], lt);
1211         //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
1212
1213         if (s.size() >= 5 && s.substr(0, 5) == "cases") {
1214                 unsigned int n = 1;
1215                 istringstream is(s.substr(5).c_str());
1216                 is >> n;
1217                 n = max(1u, n);
1218                 niceInsert(MathAtom(new MathCasesInset(n)));
1219                 return true;
1220         }
1221
1222         if (s.size() >= 6 && s.substr(0, 6) == "matrix") {
1223                 unsigned int m = 1;
1224                 unsigned int n = 1;
1225                 string v_align;
1226                 string h_align;
1227                 istringstream is(s.substr(6).c_str());
1228                 is >> m >> n >> v_align >> h_align;
1229                 m = max(1u, m);
1230                 n = max(1u, n);
1231                 v_align += 'c';
1232                 niceInsert(MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
1233                 return true;
1234         }
1235
1236         if (s.size() >= 7 && s.substr(0, 7) == "replace") {
1237                 ReplaceData rep;
1238                 istringstream is(s.substr(7).c_str());
1239                 string from, to;
1240                 is >> from >> to;
1241                 mathed_parse_cell(rep.from, from);
1242                 mathed_parse_cell(rep.to, to);
1243                 lyxerr << "replacing '" << from << "' with '" << to << "'\n";
1244                 par()->replace(rep);
1245                 return true;
1246         }
1247
1248         string name = s.substr(1);
1249
1250         if (name == "over" || name == "choose" || name == "atop") {
1251                 MathAtom t(createMathInset(name));
1252                 t->asNestInset()->cell(0) = array();
1253                 array().clear();
1254                 pos() = 0;
1255                 niceInsert(t);
1256                 popRight();
1257                 left();
1258                 return true;
1259         }
1260
1261         // prevent entering of recursive macros
1262         if (formula()->lyxCode() == Inset::MATHMACRO_CODE
1263                 && formula()->getInsetName() == name)
1264         {
1265                 lyxerr << "can't enter recursive macro\n";
1266                 return true;
1267         }
1268
1269         niceInsert(createMathInset(name));
1270         return true;
1271 }
1272
1273
1274 bool MathCursor::script(bool up)
1275 {
1276         // Hack to get \\^ and \\_ working
1277         if (inMacroMode() && macroName() == "\\") {
1278                 if (up)
1279                         interpret("\\mathcircumflex");
1280                 else
1281                         interpret('_');
1282                 return true;
1283         }
1284
1285         macroModeClose();
1286         MathGridInset safe = grabAndEraseSelection();
1287         if (inNucleus()) {
1288                 // we are in a nucleus of a script inset, move to _our_ script
1289                 par()->asScriptInset()->ensure(up);
1290                 idx() = up;
1291                 pos() = 0;
1292         } else if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1293                 prevAtom()->asScriptInset()->ensure(up);
1294                 pushRight(prevAtom());
1295                 idx() = up;
1296                 pos() = size();
1297         } else if (hasPrevAtom()) {
1298                 --pos();
1299                 array()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1300                 pushLeft(nextAtom());
1301                 idx() = up;
1302                 pos() = 0;
1303         } else {
1304                 plainInsert(MathAtom(new MathScriptInset(up)));
1305                 prevAtom()->asScriptInset()->ensure(up);
1306                 pushRight(prevAtom());
1307                 idx() = up;
1308                 pos() = 0;
1309         }
1310         paste(safe);
1311         dump("1");
1312         return true;
1313 }
1314
1315
1316 bool MathCursor::interpret(char c)
1317 {
1318         //lyxerr << "interpret 2: '" << c << "'\n";
1319         targetx_ = -1; // "no target"
1320         if (inMacroArgMode()) {
1321                 --pos();
1322                 plainErase();
1323                 int n = c - '0';
1324                 MathMacroTemplate * p = formula()->par()->asMacroTemplate();
1325                 if (p && 1 <= n && n <= p->numargs())
1326                         insert(MathAtom(new MathMacroArgument(c - '0')));
1327                 else {
1328                         insert(createMathInset("#"));
1329                         interpret(c); // try again
1330                 }
1331                 return true;
1332         }
1333
1334         // handle macroMode
1335         if (inMacroMode()) {
1336                 string name = macroName();
1337                 //lyxerr << "interpret name: '" << name << "'\n";
1338
1339                 if (name.empty() && c == '\\') {
1340                         backspace();
1341                         interpret("\\backslash");
1342                         return true;
1343                 }
1344
1345                 if (isalpha(c)) {
1346                         inMacroMode()->setName(inMacroMode()->name() + c);
1347                         return true;
1348                 }
1349
1350                 // handle 'special char' macros
1351                 if (name == "\\") {
1352                         // remove the '\\'
1353                         backspace();
1354                         if (c == '\\')
1355                                 interpret("\\backslash");
1356                         else
1357                                 interpret(string("\\") + c);
1358                         return true;
1359                 }
1360
1361                 // leave macro mode and try again if necessary
1362                 macroModeClose();
1363                 if (c != ' ')
1364                         interpret(c);
1365                 return true;
1366         }
1367
1368         // This is annoying as one has to press <space> far too often.
1369         // Disable it.
1370
1371         if (0) {
1372                 // leave autocorrect mode if necessary
1373                 if (autocorrect_ && c == ' ') {
1374                         autocorrect_ = false;
1375                         return true;
1376                 }
1377         }
1378
1379         // just clear selection on pressing the space bar
1380         if (selection_ && c == ' ') {
1381                 selection_ = false;
1382                 return true;
1383         }
1384
1385         selClearOrDel();
1386
1387         if (c == '\\') {
1388                 //lyxerr << "starting with macro\n";
1389                 insert(MathAtom(new MathUnknownInset("\\", false)));
1390                 return true;
1391         }
1392
1393         if (c == '\n') {
1394                 if (currentMode() == MathInset::TEXT_MODE) 
1395                         insert(c);
1396                 return true;
1397         }
1398
1399         if (c == ' ') {
1400                 if (currentMode() == MathInset::TEXT_MODE) {
1401                         // insert spaces in text mode,
1402                         // but suppress direct insertion of two spaces in a row
1403                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1404                         // it is better than nothing...
1405                         if (!hasPrevAtom() || prevAtom()->getChar() != ' ')
1406                                 insert(c);
1407                         return true;
1408                 }
1409                 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1410                         prevAtom()->asSpaceInset()->incSpace();
1411                         return true;
1412                 }
1413                 if (popRight())
1414                         return true;
1415                 // if are at the very end, leave the formula
1416                 return pos() != size();
1417         }
1418
1419         if (c == '#') {
1420                 insert(c); // LM_TC_TEX;
1421                 return true;
1422         }
1423
1424 /*
1425         if (c == '{' || c == '}', c)) {
1426                 insert(c); // LM_TC_TEX;
1427                 return true;
1428         }
1429 */
1430
1431         if (c == '{') {
1432                 niceInsert(MathAtom(new MathBraceInset));
1433                 return true;
1434         }
1435
1436         if (c == '}') {
1437                 return true;
1438         }
1439
1440         if (c == '$') {
1441                 insert(createMathInset("$"));
1442                 return true;
1443         }
1444
1445         if (c == '%') {
1446                 insert(createMathInset("%"));
1447                 return true;
1448         }
1449
1450 /*
1451         if (isalpha(c) && lastcode_ == LM_TC_GREEK) {
1452                 insert(c, LM_TC_VAR);
1453                 return true;
1454         }
1455
1456         if (isalpha(c) && lastcode_ == LM_TC_GREEK1) {
1457                 insert(c, LM_TC_VAR);
1458                 lastcode_ = LM_TC_VAR;
1459                 return true;
1460         }
1461
1462         if (c == '\\') {
1463                 insert(c, LM_TC_TEX);
1464                 //bv->owner()->message(_("TeX mode"));
1465                 return true;
1466         }
1467 */
1468
1469         // try auto-correction
1470         //if (autocorrect_ && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1471         //      return true;
1472
1473         // no special circumstances, so insert the character without any fuss
1474         insert(c);
1475         autocorrect_ = true;
1476         return true;
1477 }
1478
1479
1480 void MathCursor::setSelection(MathIterator const & where, size_type n)
1481 {
1482         selection_ = true;
1483         Anchor_ = where;
1484         Cursor_ = where;
1485         cursor().pos_ += n;
1486 }
1487
1488
1489 void MathCursor::insetToggle()
1490 {
1491         if (hasNextAtom()) {
1492                 // toggle previous inset ...
1493                 nextAtom()->lock(!nextAtom()->lock());
1494         } else if (popLeft() && hasNextAtom()) {
1495                 // ... or enclosing inset if we are in the last inset position
1496                 nextAtom()->lock(!nextAtom()->lock());
1497                 posRight();
1498         }
1499 }
1500
1501
1502 string MathCursor::info() const
1503 {
1504         ostringstream os;
1505         os << "Math editor mode.  ";
1506         for (int i = 0, n = depth(); i < n; ++i) {
1507                 Cursor_[i].par_->infoize(os);
1508                 os << "  ";
1509         }
1510         if (hasPrevAtom())
1511                 if (prevAtom()->asSymbolInset() || prevAtom()->asScriptInset())
1512                         prevAtom()->infoize(os);
1513         os << "                    ";
1514         return os.str().c_str(); // .c_str() needed for lyxstring
1515 }
1516
1517
1518 unsigned MathCursor::depth() const
1519 {
1520         return Cursor_.size();
1521 }
1522
1523
1524
1525
1526 namespace {
1527
1528 void region(MathCursorPos const & i1, MathCursorPos const & i2,
1529         MathInset::row_type & r1, MathInset::row_type & r2,
1530         MathInset::col_type & c1, MathInset::col_type & c2)
1531 {
1532         MathInset * p = i1.par_;
1533         c1 = p->col(i1.idx_);
1534         c2 = p->col(i2.idx_);
1535         if (c1 > c2)
1536                 swap(c1, c2);
1537         r1 = p->row(i1.idx_);
1538         r2 = p->row(i2.idx_);
1539         if (r1 > r2)
1540                 swap(r1, r2);
1541 }
1542
1543 }
1544
1545
1546 MathGridInset MathCursor::grabSelection() const
1547 {
1548         if (!selection_)
1549                 return MathGridInset();
1550         MathCursorPos i1;
1551         MathCursorPos i2;
1552         getSelection(i1, i2);
1553         // shouldn't we assert on i1.par_ == i2.par_?
1554         if (i1.idx_ == i2.idx_) {
1555                 MathGridInset data(1, 1);
1556                 MathArray::const_iterator it = i1.cell().begin();
1557                 data.cell(0) = MathArray(it + i1.pos_, it + i2.pos_);
1558                 return data;
1559         }
1560         row_type r1, r2;
1561         col_type c1, c2;
1562         region(i1, i2, r1, r2, c1, c2);
1563         MathGridInset data(c2 - c1 + 1, r2 - r1 + 1);
1564         for (row_type row = 0; row < data.nrows(); ++row)
1565                 for (col_type col = 0; col < data.ncols(); ++col) {
1566                         idx_type i = i1.par_->index(row + r1, col + c1);
1567                         data.cell(data.index(row, col)) = i1.par_->cell(i);
1568                 }
1569         return data;
1570 }
1571
1572
1573 void MathCursor::eraseSelection()
1574 {
1575         MathCursorPos i1;
1576         MathCursorPos i2;
1577         getSelection(i1, i2);
1578         if (i1.idx_ == i2.idx_)
1579                 i1.cell().erase(i1.pos_, i2.pos_);
1580         else {
1581                 MathInset * p = i1.par_;
1582                 row_type r1, r2;
1583                 col_type c1, c2;
1584                 region(i1, i2, r1, r2, c1, c2);
1585                 for (row_type row = r1; row <= r2; ++row)
1586                         for (col_type col = c1; col <= c2; ++col)
1587                                 p->cell(p->index(row, col)).clear();
1588         }
1589         cursor() = i1;
1590 }
1591
1592
1593 MathGridInset MathCursor::grabAndEraseSelection()
1594 {
1595         if (!selection_)
1596                 return MathGridInset();
1597         MathGridInset res = grabSelection();
1598         eraseSelection();
1599         selection_ = false;
1600         return res;
1601 }
1602
1603
1604 MathCursorPos MathCursor::normalAnchor() const
1605 {
1606         if (Anchor_.size() < depth()) {
1607                 Anchor_ = Cursor_;
1608                 lyxerr << "unusual Anchor size\n";
1609         }
1610         //lyx::Assert(Anchor_.size() >= cursor.depth());
1611         // use Anchor on the same level as Cursor
1612         MathCursorPos normal = Anchor_[depth() - 1];
1613         if (depth() < Anchor_.size() && !(normal < cursor())) {
1614                 // anchor is behind cursor -> move anchor behind the inset
1615                 ++normal.pos_;
1616         }
1617         return normal;
1618 }
1619
1620
1621
1622 void MathCursor::handleExtern(const string & arg)
1623 {
1624         string lang;
1625         string extra;
1626         istringstream iss(arg.c_str());
1627         iss >> lang >> extra;
1628         if (extra.empty())
1629                 extra = "noextra";
1630
1631
1632         if (selection()) {
1633                 MathArray ar;
1634                 selGet(ar);
1635                 lyxerr << "use selection: " << ar << "\n";
1636                 insert(pipeThroughExtern(lang, extra, ar));
1637                 return;
1638         }
1639
1640         MathArray eq;
1641         eq.push_back(MathAtom(new MathCharInset('=')));
1642
1643         popToEnclosingHull();
1644
1645         idx_type idx = 0;
1646         MathHullInset * hull = enclosingHull(idx);
1647         lyx::Assert(hull);
1648         idxLineFirst();
1649
1650         if (hull->getType() == "simple") {
1651                 MathArray::size_type pos = cursor().cell().find_last(eq);
1652                 MathArray ar;
1653                 if (pos == size()) {
1654                         ar = array();
1655                         lyxerr << "use whole cell: " << ar << "\n";
1656                 } else {
1657                         ar = MathArray(array().begin() + pos + 1, array().end());
1658                         lyxerr << "use partial cell form pos: " << pos << "\n";
1659                 }
1660                 end();
1661                 insert(eq);
1662                 insert(pipeThroughExtern(lang, extra, ar));
1663                 return;
1664         }
1665
1666         if (hull->getType() == "equation") {
1667                 lyxerr << "use equation inset\n";
1668                 hull->mutate("eqnarray");
1669                 MathArray & ar = cursor().cell();
1670                 lyxerr << "use cell: " << ar << "\n";
1671                 idxRight();
1672                 cursor().cell() = eq;
1673                 idxRight();
1674                 cursor().cell() = pipeThroughExtern(lang, extra, ar);
1675                 idxLineLast();
1676                 return;
1677         }
1678
1679         {
1680                 lyxerr << "use eqnarray\n";
1681                 idxLineLast();
1682                 MathArray ar = cursor().cell();
1683                 lyxerr << "use cell: " << ar << "\n";
1684                 breakLine();
1685                 idxRight();
1686                 cursor().cell() = eq;
1687                 idxRight();
1688                 cursor().cell() = pipeThroughExtern(lang, extra, ar);
1689                 idxLineLast();
1690         }
1691
1692 }
1693
1694
1695 int MathCursor::dispatch(string const & cmd)
1696 {
1697         // try to dispatch to adajcent items if they are not editable
1698         // actually, this should only happen for mouse clicks...
1699         if (hasNextAtom() && !openable(nextAtom(), false))
1700                 if (int res = nextAtom()->dispatch(cmd, 0, 0))
1701                         return res;
1702         if (hasPrevAtom() && !openable(prevAtom(), false))
1703                 if (int res = prevAtom()->dispatch(cmd, 0, 0))
1704                         return res;
1705
1706         for (int i = Cursor_.size() - 1; i >= 0; --i) {
1707                 MathCursorPos & pos = Cursor_[i];
1708                 if (int res = pos.par_->dispatch(cmd, pos.idx_, pos.pos_))
1709                         return res;
1710         }
1711         return 0;
1712 }
1713
1714
1715 MathInset::mode_type MathCursor::currentMode() const
1716 {
1717         for (int i = Cursor_.size() - 1; i >= 0; --i) {
1718                 MathInset::mode_type res = Cursor_[i].par_->currentMode();
1719                 if (res != MathInset::UNDECIDED_MODE)
1720                         return res;
1721         }
1722         return MathInset::UNDECIDED_MODE;
1723 }
1724
1725
1726 void releaseMathCursor(BufferView * bv)
1727 {
1728         if (!mathcursor)
1729                 return;
1730         mathcursor->formula()->hideInsetCursor(bv);
1731         delete mathcursor;
1732         mathcursor = 0;
1733 }