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