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