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