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