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