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