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