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