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