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