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