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