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