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