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