]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
Look for mathed xpms. Doesn't do anything yet due to lack of workable XPMs
[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         array().insert(pos(), ar);
399         pos() += ar.size();
400 }
401
402
403 void MathCursor::paste(MathGridInset const & data)
404 {
405         ostringstream os;
406   WriteStream wi(os, false, false);
407   data.write(wi);
408         dispatch(FuncRequest(LFUN_PASTE, os.str()));
409 }
410
411
412 void MathCursor::backspace()
413 {
414         autocorrect_ = false;
415         if (pos() == 0) {
416                 pullArg();
417                 return;
418         }
419
420         if (selection_) {
421                 selDel();
422                 return;
423         }
424
425         if (inMacroMode()) {
426                 MathUnknownInset * p = activeMacro();
427                 if (p->name().size() > 1) {
428                         p->setName(p->name().substr(0, p->name().size() - 1));
429                         return;
430                 }
431         }
432
433 /*
434         if (prevAtom()->asScriptInset()) {
435                 // simply enter nucleus
436                 left();
437                 return;
438         }
439
440         if (inNucleus()) {
441                 // we are in nucleus
442                 if (pos() == 1) {
443                 }
444         }
445 */
446
447         --pos();
448         plainErase();
449 }
450
451
452 void MathCursor::erase()
453 {
454         autocorrect_ = false;
455         if (inMacroMode())
456                 return;
457
458         if (selection_) {
459                 selDel();
460                 return;
461         }
462
463         // delete empty cells if possible
464         if (array().empty())
465                 if (par()->idxDelete(idx()))
466                         return;
467
468         // old behaviour when in last position of cell
469         if (pos() == size()) {
470                 par()->idxGlue(idx());
471                 return;
472         }
473
474 /*
475         // if we are standing in front of a script inset, grab item before us and
476         // move it into nucleus
477         // and remove first thing.
478         if (hasNextAtom() && nextAtom()->asScriptInset()) {
479                 if (hasPrevAtom()) {
480                         MathAtom at = prevAtom();
481                         --pos();
482                         array().erase(pos());
483                         pushLeft(nextAtom());
484                         if (array().empty())
485                                 array().push_back(at);
486                         else
487                                 array()[0] = at;
488                         pos() = 1;
489                 } else {
490                         pushLeft(nextAtom());
491                         array().clear();
492                 }
493                 return;
494         }
495 */
496
497         plainErase();
498 }
499
500
501 bool MathCursor::up(bool sel)
502 {
503         dump("up 1");
504         macroModeClose();
505         selHandle(sel);
506         MathIterator save = Cursor_;
507         if (goUpDown(true))
508                 return true;
509         Cursor_ = save;
510         autocorrect_ = false;
511         return selection_;
512 }
513
514
515 bool MathCursor::down(bool sel)
516 {
517         dump("down 1");
518         macroModeClose();
519         selHandle(sel);
520         MathIterator save = Cursor_;
521         if (goUpDown(false))
522                 return true;
523         Cursor_ = save;
524         autocorrect_ = false;
525         return selection_;
526 }
527
528
529 void MathCursor::macroModeClose()
530 {
531         if (!inMacroMode())
532                 return;
533         MathUnknownInset * p = activeMacro();
534         p->finalize();
535         string s = p->name();
536         --pos();
537         array().erase(pos());
538         if (s != "\\")
539                 interpret(s);
540 }
541
542
543 string MathCursor::macroName() const
544 {
545         return inMacroMode() ? activeMacro()->name() : string();
546 }
547
548
549 void MathCursor::selClear()
550 {
551         Anchor_.clear();
552         selection_ = false;
553 }
554
555
556 void MathCursor::selCopy()
557 {
558         dump("selCopy");
559         if (selection_) {
560                 theCutBuffer = grabSelection();
561                 selection_ = false;
562         } else {
563                 theCutBuffer = MathGridInset(1, 1);
564         }
565 }
566
567
568 void MathCursor::selCut()
569 {
570         dump("selCut");
571         theCutBuffer = grabAndEraseSelection();
572 }
573
574
575 void MathCursor::selDel()
576 {
577         dump("selDel");
578         if (selection_) {
579                 eraseSelection();
580                 selection_ = false;
581         }
582 }
583
584
585 void MathCursor::selPaste()
586 {
587         dump("selPaste");
588         selClearOrDel();
589         paste(theCutBuffer);
590         //grabSelection();
591         selection_ = false;
592 }
593
594
595 void MathCursor::selHandle(bool sel)
596 {
597         if (sel == selection_)
598                 return;
599         //clear();
600         Anchor_ = Cursor_;
601         selection_ = sel;
602 }
603
604
605 void MathCursor::selStart()
606 {
607         dump("selStart 1");
608         //clear();
609         Anchor_ = Cursor_;
610         selection_ = true;
611         dump("selStart 2");
612 }
613
614
615 void MathCursor::selClearOrDel()
616 {
617         if (lyxrc.auto_region_delete)
618                 selDel();
619         else
620                 selection_ = false;
621 }
622
623
624 void MathCursor::selGet(MathArray & ar)
625 {
626         dump("selGet");
627         if (selection_)
628                 ar = grabSelection().glue();
629 }
630
631
632 void MathCursor::drawSelection(MathPainterInfo & pi) const
633 {
634         if (!selection_)
635                 return;
636         MathCursorPos i1;
637         MathCursorPos i2;
638         getSelection(i1, i2);
639         i1.par_->drawSelection(pi, i1.idx_, i1.pos_, i2.idx_, i2.pos_);
640 }
641
642
643 void MathCursor::handleNest(MathAtom const & a)
644 {
645         MathAtom at = a;
646         at.nucleus()->cell(0) = grabAndEraseSelection().glue();
647         insert(at);
648         pushRight(prevAtom());
649 }
650
651
652 void MathCursor::getPos(int & x, int & y) const
653 {
654         par()->getPos(idx(), pos(), x, y);
655 }
656
657
658 int MathCursor::targetX() const
659 {
660         if (targetx_ != -1)
661                 return targetx_;
662         int x = 0, y = 0;
663         getPos(x, y);
664         return x;
665 }
666
667
668 MathInset * MathCursor::par() const
669 {
670         return cursor().par_;
671 }
672
673
674 InsetFormulaBase * MathCursor::formula() const
675 {
676         return formula_;
677 }
678
679
680 MathCursor::idx_type MathCursor::idx() const
681 {
682         return cursor().idx_;
683 }
684
685
686 MathCursor::idx_type & MathCursor::idx()
687 {
688         return cursor().idx_;
689 }
690
691
692 MathCursor::pos_type MathCursor::pos() const
693 {
694         return cursor().pos_;
695 }
696
697
698 MathCursor::pos_type & MathCursor::pos()
699 {
700         return cursor().pos_;
701 }
702
703
704 bool MathCursor::inMacroMode() const
705 {
706         if (!hasPrevAtom())
707                 return false;
708         MathUnknownInset const * p = prevAtom()->asUnknownInset();
709         return p && !p->final();
710 }
711
712
713 MathUnknownInset * MathCursor::activeMacro()
714 {
715         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
716 }
717
718
719 MathUnknownInset const * MathCursor::activeMacro() const
720 {
721         return inMacroMode() ? prevAtom()->asUnknownInset() : 0;
722 }
723
724
725 bool MathCursor::inMacroArgMode() const
726 {
727         return pos() > 0 && prevAtom()->getChar() == '#';
728 }
729
730
731 bool MathCursor::selection() const
732 {
733         return selection_;
734 }
735
736
737 MathGridInset * MathCursor::enclosingGrid(MathCursor::idx_type & idx) const
738 {
739         for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
740                 MathGridInset * p = Cursor_[i].par_->asGridInset();
741                 if (p) {
742                         idx = Cursor_[i].idx_;
743                         return p;
744                 }
745         }
746         return 0;
747 }
748
749
750 void MathCursor::popToHere(MathInset const * p)
751 {
752         while (depth() && Cursor_.back().par_ != p)
753                 Cursor_.pop_back();
754 }
755
756
757 void MathCursor::popToEnclosingGrid()
758 {
759         while (depth() && !Cursor_.back().par_->asGridInset())
760                 Cursor_.pop_back();
761 }
762
763
764 void MathCursor::popToEnclosingHull()
765 {
766         while (depth() && !Cursor_.back().par_->asHullInset())
767                 Cursor_.pop_back();
768 }
769
770
771 void MathCursor::pullArg()
772 {
773         dump("pullarg");
774         MathArray a = array();
775         if (popLeft()) {
776                 plainErase();
777                 array().insert(pos(), a);
778                 Anchor_ = Cursor_;
779         } else {
780                 formula()->mutateToText();
781         }
782 }
783
784
785 void MathCursor::touch()
786 {
787         MathIterator::const_iterator it = Cursor_.begin();
788         MathIterator::const_iterator et = Cursor_.end();
789         for ( ; it != et; ++it)
790                 it->cell().touch();
791 }
792
793
794 void MathCursor::normalize()
795 {
796         if (idx() >= par()->nargs()) {
797                 lyxerr << "this should not really happen - 1: "
798                        << idx() << " " << par()->nargs() << " in: " << par() << "\n";
799                 dump("error 2");
800         }
801         idx() = min(idx(), par()->nargs() - 1);
802
803         if (pos() > size()) {
804                 lyxerr << "this should not really happen - 2: "
805                         << pos() << " " << size() <<  " in idx: " << idx()
806                         << " in atom: '";
807                 WriteStream wi(lyxerr, false, true);
808                 par()->write(wi);
809                 lyxerr << "\n";
810                 dump("error 4");
811         }
812         pos() = min(pos(), size());
813
814         // remove empty scripts if possible
815         if (1) {
816                 for (pos_type i = 0; i < size(); ++i) {
817                         MathScriptInset * p = array()[i].nucleus()->asScriptInset();
818                         if (p) {
819                                 p->removeEmptyScripts();
820                                 //if (p->empty())
821                                 //      array().erase(i);
822                         }
823                 }
824         }
825
826         // fix again position
827         pos() = min(pos(), size());
828 }
829
830
831 MathCursor::size_type MathCursor::size() const
832 {
833         return array().size();
834 }
835
836
837 bool MathCursor::hasPrevAtom() const
838 {
839         return pos() > 0;
840 }
841
842
843 bool MathCursor::hasNextAtom() const
844 {
845         return pos() < size();
846 }
847
848
849 MathAtom const & MathCursor::prevAtom() const
850 {
851         lyx::Assert(pos() > 0);
852         return array()[pos() - 1];
853 }
854
855
856 MathAtom & MathCursor::prevAtom()
857 {
858         lyx::Assert(pos() > 0);
859         return array()[pos() - 1];
860 }
861
862
863 MathAtom const & MathCursor::nextAtom() const
864 {
865         lyx::Assert(pos() < size());
866         return array()[pos()];
867 }
868
869
870 MathAtom & MathCursor::nextAtom()
871 {
872         lyx::Assert(pos() < size());
873         return array()[pos()];
874 }
875
876
877 MathArray & MathCursor::array() const
878 {
879         static MathArray dummy;
880
881         if (idx() >= par()->nargs()) {
882                 lyxerr << "############  idx_ " << idx() << " not valid\n";
883                 return dummy;
884         }
885
886         if (depth() == 0) {
887                 lyxerr << "############  depth() == 0 not valid\n";
888                 return dummy;
889         }
890
891         return cursor().cell();
892 }
893
894
895 void MathCursor::idxNext()
896 {
897         par()->idxNext(idx(), pos());
898 }
899
900
901 void MathCursor::idxPrev()
902 {
903         par()->idxPrev(idx(), pos());
904 }
905
906
907 char MathCursor::valign() const
908 {
909         idx_type idx;
910         MathGridInset * p = enclosingGrid(idx);
911         return p ? p->valign() : '\0';
912 }
913
914
915 char MathCursor::halign() const
916 {
917         idx_type idx;
918         MathGridInset * p = enclosingGrid(idx);
919         return p ? p->halign(idx % p->ncols()) : '\0';
920 }
921
922
923 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
924 {
925         MathCursorPos anc = normalAnchor();
926         if (anc < cursor()) {
927                 i1 = anc;
928                 i2 = cursor();
929         } else {
930                 i1 = cursor();
931                 i2 = anc;
932         }
933 }
934
935
936 MathCursorPos & MathCursor::cursor()
937 {
938         lyx::Assert(depth());
939         return Cursor_.back();
940 }
941
942
943 MathCursorPos const & MathCursor::cursor() const
944 {
945         lyx::Assert(depth());
946         return Cursor_.back();
947 }
948
949
950 bool MathCursor::goUpDown(bool up)
951 {
952         // Be warned: The 'logic' implemented in this function is highly fragile.
953         // A distance of one pixel or a '<' vs '<=' _really_ matters.
954         // So fiddle around with it only if you know what you are doing!
955   int xo = 0;
956         int yo = 0;
957         getPos(xo, yo);
958
959         // check if we had something else in mind, if not, this is the future goal
960         if (targetx_ == -1)
961                 targetx_ = xo;
962         else
963                 xo = targetx_;
964
965         // try neigbouring script insets
966         // try left
967         if (hasPrevAtom()) {
968                 MathScriptInset const * p = prevAtom()->asScriptInset();
969                 if (p && p->has(up)) {
970                         --pos();
971                         push(nextAtom());
972                         idx() = up; // the superscript has index 1
973                         pos() = size();
974                         ///lyxerr << "updown: handled by scriptinset to the left\n";
975                         return true;
976                 }
977         }
978
979         // try right
980         if (hasNextAtom()) {
981                 MathScriptInset const * p = nextAtom()->asScriptInset();
982                 if (p && p->has(up)) {
983                         push(nextAtom());
984                         idx() = up;
985                         pos() = 0;
986                         ///lyxerr << "updown: handled by scriptinset to the right\n";
987                         return true;
988                 }
989         }
990
991         // try current cell
992         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
993         //if (up)
994         //      yhigh = yo - 4;
995         //else
996         //      ylow = yo + 4;
997         //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
998         //      lyxerr << "updown: handled by brute find in the same cell\n";
999         //      return true;
1000         //}
1001
1002         // try to find an inset that knows better then we
1003         while (1) {
1004                 ///lyxerr << "updown: We are in " << *par() << " idx: " << idx() << '\n';
1005                 // ask inset first
1006                 if (par()->idxUpDown(idx(), pos(), up, targetx_))
1007                         return true;
1008
1009                 // no such inset found, just take something "above"
1010                 ///lyxerr << "updown: handled by strange case\n";
1011                 if (!popLeft())
1012                         return
1013                                 bruteFind(xo, yo,
1014                                         formula()->xlow(),
1015                                         formula()->xhigh(),
1016                                         up ? formula()->ylow() : yo + 4,
1017                                         up ? yo - 4 : formula()->yhigh()
1018                                 );
1019
1020                 // any improvement so far?
1021                 int xnew, ynew;
1022                 getPos(xnew, ynew);
1023                 if (up ? ynew < yo : ynew > yo)
1024                         return true;
1025         }
1026 }
1027
1028
1029 bool MathCursor::bruteFind
1030         (int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1031 {
1032         MathIterator best_cursor;
1033         double best_dist = 1e10;
1034
1035         MathIterator it = ibegin(formula()->par().nucleus());
1036         MathIterator et = iend(formula()->par().nucleus());
1037         while (1) {
1038                 // avoid invalid nesting when selecting
1039                 if (!selection_ || positionable(it, Anchor_)) {
1040                         int xo, yo;
1041                         it.back().getPos(xo, yo);
1042                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1043                                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1044                                 // '<=' in order to take the last possible position
1045                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1046                                 if (d <= best_dist) {
1047                                         best_dist   = d;
1048                                         best_cursor = it;
1049                                 }
1050                         }
1051                 }
1052
1053                 if (it == et)
1054                         break;
1055                 ++it;
1056         }
1057
1058         if (best_dist < 1e10)
1059                 Cursor_ = best_cursor;
1060         return best_dist < 1e10;
1061 }
1062
1063
1064 bool MathCursor::idxLineLast()
1065 {
1066         idx() -= idx() % par()->ncols();
1067         idx() += par()->ncols() - 1;
1068         pos() = size();
1069         return true;
1070 }
1071
1072 bool MathCursor::idxLeft()
1073 {
1074         return par()->idxLeft(idx(), pos());
1075 }
1076
1077
1078 bool MathCursor::idxRight()
1079 {
1080         return par()->idxRight(idx(), pos());
1081 }
1082
1083
1084 bool MathCursor::interpret(string const & s)
1085 {
1086         //lyxerr << "interpret 1: '" << s << "'\n";
1087         if (s.empty())
1088                 return true;
1089
1090         //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
1091         //owner_->getIntl()->getTransManager().TranslateAndInsert(s[0], lt);
1092         //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
1093
1094         if (s.size() >= 6 && s.substr(0, 6) == "matrix") {
1095                 unsigned int m = 1;
1096                 unsigned int n = 1;
1097                 string v_align;
1098                 string h_align;
1099                 istringstream is(s.substr(6).c_str());
1100                 is >> m >> n >> v_align >> h_align;
1101                 m = max(1u, m);
1102                 n = max(1u, n);
1103                 v_align += 'c';
1104                 niceInsert(MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
1105                 return true;
1106         }
1107
1108         if (s.size() >= 7 && s.substr(0, 7) == "replace") {
1109                 ReplaceData rep;
1110                 istringstream is(s.substr(7).c_str());
1111                 string from, to;
1112                 is >> from >> to;
1113                 mathed_parse_cell(rep.from, from);
1114                 mathed_parse_cell(rep.to, to);
1115                 lyxerr << "replacing '" << from << "' with '" << to << "'\n";
1116                 par()->replace(rep);
1117                 return true;
1118         }
1119
1120         string name = s.substr(1);
1121
1122         if (name == "over" || name == "choose" || name == "atop") {
1123                 MathAtom t(createMathInset(name));
1124                 t.nucleus()->asNestInset()->cell(0) = array();
1125                 array().clear();
1126                 pos() = 0;
1127                 niceInsert(t);
1128                 popRight();
1129                 left();
1130                 return true;
1131         }
1132
1133         // prevent entering of recursive macros
1134         if (formula()->lyxCode() == Inset::MATHMACRO_CODE
1135                 && formula()->getInsetName() == name)
1136         {
1137                 lyxerr << "can't enter recursive macro\n";
1138                 return true;
1139         }
1140
1141         niceInsert(createMathInset(name));
1142         return true;
1143 }
1144
1145
1146 bool MathCursor::script(bool up)
1147 {
1148         // Hack to get \\^ and \\_ working
1149         if (inMacroMode() && macroName() == "\\") {
1150                 if (up)
1151                         niceInsert(createMathInset("mathcircumflex"));
1152                 else
1153                         interpret('_');
1154                 return true;
1155         }
1156
1157         macroModeClose();
1158         MathGridInset safe = grabAndEraseSelection();
1159         if (inNucleus()) {
1160                 // we are in a nucleus of a script inset, move to _our_ script
1161                 par()->asScriptInset()->ensure(up);
1162                 idx() = up;
1163                 pos() = 0;
1164         } else if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1165                 prevAtom().nucleus()->asScriptInset()->ensure(up);
1166                 pushRight(prevAtom());
1167                 idx() = up;
1168                 pos() = size();
1169         } else if (hasPrevAtom()) {
1170                 --pos();
1171                 array()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1172                 pushLeft(nextAtom());
1173                 idx() = up;
1174                 pos() = 0;
1175         } else {
1176                 plainInsert(MathAtom(new MathScriptInset(up)));
1177                 prevAtom().nucleus()->asScriptInset()->ensure(up);
1178                 pushRight(prevAtom());
1179                 idx() = up;
1180                 pos() = 0;
1181         }
1182         paste(safe);
1183         dump("1");
1184         return true;
1185 }
1186
1187
1188 bool MathCursor::interpret(char c)
1189 {
1190         //lyxerr << "interpret 2: '" << c << "'\n";
1191         targetx_ = -1; // "no target"
1192         if (inMacroArgMode()) {
1193                 --pos();
1194                 plainErase();
1195                 int n = c - '0';
1196                 MathMacroTemplate const * p = formula()->par()->asMacroTemplate();
1197                 if (p && 1 <= n && n <= p->numargs())
1198                         insert(MathAtom(new MathMacroArgument(c - '0')));
1199                 else {
1200                         insert(createMathInset("#"));
1201                         interpret(c); // try again
1202                 }
1203                 return true;
1204         }
1205
1206         // handle macroMode
1207         if (inMacroMode()) {
1208                 string name = macroName();
1209                 //lyxerr << "interpret name: '" << name << "'\n";
1210
1211                 if (isalpha(c)) {
1212                         activeMacro()->setName(activeMacro()->name() + c);
1213                         return true;
1214                 }
1215
1216                 // handle 'special char' macros
1217                 if (name == "\\") {
1218                         // remove the '\\'
1219                         backspace();
1220                         if (c == '\\') {
1221                                 if (currentMode() == MathInset::TEXT_MODE)
1222                                         niceInsert(createMathInset("textbackslash"));
1223                                 else
1224                                         niceInsert(createMathInset("backslash"));
1225                         } else
1226                                 niceInsert(createMathInset(string(1, c)));
1227                         return true;
1228                 }
1229
1230                 // leave macro mode and try again if necessary
1231                 macroModeClose();
1232                 if (c != ' ')
1233                         interpret(c);
1234                 return true;
1235         }
1236
1237         // This is annoying as one has to press <space> far too often.
1238         // Disable it.
1239
1240         if (0) {
1241                 // leave autocorrect mode if necessary
1242                 if (autocorrect_ && c == ' ') {
1243                         autocorrect_ = false;
1244                         return true;
1245                 }
1246         }
1247
1248         // just clear selection on pressing the space bar
1249         if (selection_ && c == ' ') {
1250                 selection_ = false;
1251                 return true;
1252         }
1253
1254         selClearOrDel();
1255
1256         if (c == '\\') {
1257                 //lyxerr << "starting with macro\n";
1258                 insert(MathAtom(new MathUnknownInset("\\", false)));
1259                 return true;
1260         }
1261
1262         if (c == '\n') {
1263                 if (currentMode() == MathInset::TEXT_MODE) 
1264                         insert(c);
1265                 return true;
1266         }
1267
1268         if (c == ' ') {
1269                 if (currentMode() == MathInset::TEXT_MODE) {
1270                         // insert spaces in text mode,
1271                         // but suppress direct insertion of two spaces in a row
1272                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1273                         // it is better than nothing...
1274                         if (!hasPrevAtom() || prevAtom()->getChar() != ' ')
1275                                 insert(c);
1276                         return true;
1277                 }
1278                 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1279                         prevAtom().nucleus()->asSpaceInset()->incSpace();
1280                         return true;
1281                 }
1282                 if (popRight())
1283                         return true;
1284                 // if are at the very end, leave the formula
1285                 return pos() != size();
1286         }
1287
1288         if (c == '#') {
1289                 insert(c); // LM_TC_TEX;
1290                 return true;
1291         }
1292
1293 /*
1294         if (c == '{' || c == '}', c)) {
1295                 insert(c); // LM_TC_TEX;
1296                 return true;
1297         }
1298 */
1299
1300         if (c == '{') {
1301                 niceInsert(MathAtom(new MathBraceInset));
1302                 return true;
1303         }
1304
1305         if (c == '}') {
1306                 return true;
1307         }
1308
1309         if (c == '$') {
1310                 insert(createMathInset("$"));
1311                 return true;
1312         }
1313
1314         if (c == '%') {
1315                 niceInsert(MathAtom(new MathCommentInset));
1316                 return true;
1317         }
1318
1319 /*
1320         if (isalpha(c) && lastcode_ == LM_TC_GREEK) {
1321                 insert(c, LM_TC_VAR);
1322                 return true;
1323         }
1324
1325         if (isalpha(c) && lastcode_ == LM_TC_GREEK1) {
1326                 insert(c, LM_TC_VAR);
1327                 lastcode_ = LM_TC_VAR;
1328                 return true;
1329         }
1330
1331         if (c == '\\') {
1332                 insert(c, LM_TC_TEX);
1333                 //bv->owner()->message(_("TeX mode"));
1334                 return true;
1335         }
1336 */
1337
1338         // try auto-correction
1339         //if (autocorrect_ && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1340         //      return true;
1341
1342         // no special circumstances, so insert the character without any fuss
1343         insert(c);
1344         autocorrect_ = true;
1345         return true;
1346 }
1347
1348
1349 void MathCursor::setSelection(MathIterator const & where, size_type n)
1350 {
1351         selection_ = true;
1352         Anchor_ = where;
1353         Cursor_ = where;
1354         cursor().pos_ += n;
1355 }
1356
1357
1358 void MathCursor::insetToggle()
1359 {
1360         if (hasNextAtom()) {
1361                 // toggle previous inset ...
1362                 nextAtom().nucleus()->lock(!nextAtom()->lock());
1363         } else if (popLeft() && hasNextAtom()) {
1364                 // ... or enclosing inset if we are in the last inset position
1365                 nextAtom().nucleus()->lock(!nextAtom()->lock());
1366                 posRight();
1367         }
1368 }
1369
1370
1371 string MathCursor::info() const
1372 {
1373         ostringstream os;
1374         os << "Math editor mode.  ";
1375         for (int i = 0, n = depth(); i < n; ++i) {
1376                 Cursor_[i].par_->infoize(os);
1377                 os << "  ";
1378         }
1379         if (hasPrevAtom())
1380                 if (prevAtom()->asSymbolInset() || prevAtom()->asScriptInset())
1381                         prevAtom()->infoize(os);
1382         os << "                    ";
1383         return os.str().c_str(); // .c_str() needed for lyxstring
1384 }
1385
1386
1387 unsigned MathCursor::depth() const
1388 {
1389         return Cursor_.size();
1390 }
1391
1392
1393
1394
1395 namespace {
1396
1397 void region(MathCursorPos const & i1, MathCursorPos const & i2,
1398         MathInset::row_type & r1, MathInset::row_type & r2,
1399         MathInset::col_type & c1, MathInset::col_type & c2)
1400 {
1401         MathInset * p = i1.par_;
1402         c1 = p->col(i1.idx_);
1403         c2 = p->col(i2.idx_);
1404         if (c1 > c2)
1405                 swap(c1, c2);
1406         r1 = p->row(i1.idx_);
1407         r2 = p->row(i2.idx_);
1408         if (r1 > r2)
1409                 swap(r1, r2);
1410 }
1411
1412 }
1413
1414
1415 MathGridInset MathCursor::grabSelection() const
1416 {
1417         if (!selection_)
1418                 return MathGridInset();
1419         MathCursorPos i1;
1420         MathCursorPos i2;
1421         getSelection(i1, i2);
1422         // shouldn't we assert on i1.par_ == i2.par_?
1423         if (i1.idx_ == i2.idx_) {
1424                 MathGridInset data(1, 1);
1425                 MathArray::const_iterator it = i1.cell().begin();
1426                 data.cell(0) = MathArray(it + i1.pos_, it + i2.pos_);
1427                 return data;
1428         }
1429         row_type r1, r2;
1430         col_type c1, c2;
1431         region(i1, i2, r1, r2, c1, c2);
1432         MathGridInset data(c2 - c1 + 1, r2 - r1 + 1);
1433         for (row_type row = 0; row < data.nrows(); ++row)
1434                 for (col_type col = 0; col < data.ncols(); ++col) {
1435                         idx_type i = i1.par_->index(row + r1, col + c1);
1436                         data.cell(data.index(row, col)) = i1.par_->cell(i);
1437                 }
1438         return data;
1439 }
1440
1441
1442 void MathCursor::eraseSelection()
1443 {
1444         MathCursorPos i1;
1445         MathCursorPos i2;
1446         getSelection(i1, i2);
1447         if (i1.idx_ == i2.idx_)
1448                 i1.cell().erase(i1.pos_, i2.pos_);
1449         else {
1450                 MathInset * p = i1.par_;
1451                 row_type r1, r2;
1452                 col_type c1, c2;
1453                 region(i1, i2, r1, r2, c1, c2);
1454                 for (row_type row = r1; row <= r2; ++row)
1455                         for (col_type col = c1; col <= c2; ++col)
1456                                 p->cell(p->index(row, col)).clear();
1457         }
1458         cursor() = i1;
1459 }
1460
1461
1462 MathGridInset MathCursor::grabAndEraseSelection()
1463 {
1464         if (!selection_)
1465                 return MathGridInset();
1466         MathGridInset res = grabSelection();
1467         eraseSelection();
1468         selection_ = false;
1469         return res;
1470 }
1471
1472
1473 MathCursorPos MathCursor::normalAnchor() const
1474 {
1475         if (Anchor_.size() < depth()) {
1476                 Anchor_ = Cursor_;
1477                 lyxerr << "unusual Anchor size\n";
1478         }
1479         //lyx::Assert(Anchor_.size() >= cursor.depth());
1480         // use Anchor on the same level as Cursor
1481         MathCursorPos normal = Anchor_[depth() - 1];
1482         if (depth() < Anchor_.size() && !(normal < cursor())) {
1483                 // anchor is behind cursor -> move anchor behind the inset
1484                 ++normal.pos_;
1485         }
1486         return normal;
1487 }
1488
1489
1490 MathInset::result_type MathCursor::dispatch(FuncRequest const & cmd)
1491 {
1492         // try to dispatch to adajcent items if they are not editable
1493         // actually, this should only happen for mouse clicks...
1494         idx_type d1;
1495         pos_type d2;
1496         if (hasNextAtom() && !openable(nextAtom(), false)) {
1497                 MathInset::result_type res = nextAtom().nucleus()->dispatch(cmd, d1, d2);
1498                 if (res != MathInset::UNDISPATCHED)
1499                         return res;
1500         }
1501         if (hasPrevAtom() && !openable(prevAtom(), false)) {
1502                 MathInset::result_type res = prevAtom().nucleus()->dispatch(cmd, d1, d2);
1503                 if (res != MathInset::UNDISPATCHED)
1504                         return res;
1505         }
1506
1507         for (int i = Cursor_.size() - 1; i >= 0; --i) {
1508                 MathCursorPos & pos = Cursor_[i];
1509                 MathInset::result_type const res
1510                         = pos.par_->dispatch(cmd, pos.idx_, pos.pos_);
1511                 if (res != MathInset::UNDISPATCHED) {
1512                         if (res == MathInset::DISPATCHED_POP) {
1513                                 Cursor_.shrink(i + 1);
1514                                 selClear();
1515                         }
1516                         return res;
1517                 }
1518         }
1519         return MathInset::UNDISPATCHED;
1520 }
1521
1522
1523 MathInset::mode_type MathCursor::currentMode() const
1524 {
1525         for (int i = Cursor_.size() - 1; i >= 0; --i) {
1526                 MathInset::mode_type res = Cursor_[i].par_->currentMode();
1527                 if (res != MathInset::UNDECIDED_MODE)
1528                         return res;
1529         }
1530         return MathInset::UNDECIDED_MODE;
1531 }
1532
1533
1534 void releaseMathCursor(BufferView * bv)
1535 {
1536         if (!mathcursor)
1537                 return;
1538         mathcursor->formula()->hideInsetCursor(bv);
1539         delete mathcursor;
1540         mathcursor = 0;
1541 }