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