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