]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
more lfun localization
[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         //cerr << "Entering atom "; t->write(cerr, false); cerr << " left\n";
96         push(t);
97         t->idxFirst(idx(), pos());
98 }
99
100
101 void MathCursor::pushRight(MathAtom & t)
102 {
103         //cerr << "Entering atom "; t->write(cerr, false); cerr << " 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 MathHullInset * MathCursor::enclosingHull(MathCursor::idx_type & idx) const
754 {
755         for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
756                 MathHullInset * p = Cursor_[i].par_->asHullInset();
757                 if (p) {
758                         idx = Cursor_[i].idx_;
759                         return p;
760                 }
761         }
762         return 0;
763 }
764
765
766 void MathCursor::popToHere(MathInset const * p)
767 {
768         while (depth() && Cursor_.back().par_ != p)
769                 Cursor_.pop_back();
770 }
771
772
773 void MathCursor::popToEnclosingGrid()
774 {
775         while (depth() && !Cursor_.back().par_->asGridInset())
776                 Cursor_.pop_back();
777 }
778
779
780 void MathCursor::popToEnclosingHull()
781 {
782         while (depth() && !Cursor_.back().par_->asHullInset())
783                 Cursor_.pop_back();
784 }
785
786
787 void MathCursor::pullArg()
788 {
789         dump("pullarg");
790         MathArray a = array();
791         if (popLeft()) {
792                 plainErase();
793                 array().insert(pos(), a);
794                 Anchor_ = Cursor_;
795         } else {
796                 formula()->mutateToText();
797         }
798 }
799
800
801 void MathCursor::touch()
802 {
803         MathIterator::const_iterator it = Cursor_.begin();
804         MathIterator::const_iterator et = Cursor_.end();
805         for ( ; it != et; ++it)
806                 it->cell().touch();
807 }
808
809
810 void MathCursor::normalize()
811 {
812         if (idx() >= par()->nargs()) {
813                 lyxerr << "this should not really happen - 1: "
814                        << idx() << " " << par()->nargs() << " in: " << par() << "\n";
815                 dump("error 2");
816         }
817         idx() = min(idx(), par()->nargs() - 1);
818
819         if (pos() > size()) {
820                 lyxerr << "this should not really happen - 2: "
821                         << pos() << " " << size() <<  " in idx: " << idx()
822                         << " in atom: '";
823                 WriteStream wi(lyxerr, false, true);
824                 par()->write(wi);
825                 lyxerr << "\n";
826                 dump("error 4");
827         }
828         pos() = min(pos(), size());
829
830         // remove empty scripts if possible
831         if (1) {
832                 for (pos_type i = 0; i < size(); ++i) {
833                         MathScriptInset * p = array()[i].nucleus()->asScriptInset();
834                         if (p) {
835                                 p->removeEmptyScripts();
836                                 //if (p->empty())
837                                 //      array().erase(i);
838                         }
839                 }
840         }
841
842         // fix again position
843         pos() = min(pos(), size());
844 }
845
846
847 MathCursor::size_type MathCursor::size() const
848 {
849         return array().size();
850 }
851
852
853 bool MathCursor::hasPrevAtom() const
854 {
855         return pos() > 0;
856 }
857
858
859 bool MathCursor::hasNextAtom() const
860 {
861         return pos() < size();
862 }
863
864
865 MathAtom const & MathCursor::prevAtom() const
866 {
867         lyx::Assert(pos() > 0);
868         return array()[pos() - 1];
869 }
870
871
872 MathAtom & MathCursor::prevAtom()
873 {
874         lyx::Assert(pos() > 0);
875         return array()[pos() - 1];
876 }
877
878
879 MathAtom const & MathCursor::nextAtom() const
880 {
881         lyx::Assert(pos() < size());
882         return array()[pos()];
883 }
884
885
886 MathAtom & MathCursor::nextAtom()
887 {
888         lyx::Assert(pos() < size());
889         return array()[pos()];
890 }
891
892
893 MathArray & MathCursor::array() const
894 {
895         static MathArray dummy;
896
897         if (idx() >= par()->nargs()) {
898                 lyxerr << "############  idx_ " << idx() << " not valid\n";
899                 return dummy;
900         }
901
902         if (depth() == 0) {
903                 lyxerr << "############  depth() == 0 not valid\n";
904                 return dummy;
905         }
906
907         return cursor().cell();
908 }
909
910
911 void MathCursor::idxNext()
912 {
913         par()->idxNext(idx(), pos());
914 }
915
916
917 void MathCursor::idxPrev()
918 {
919         par()->idxPrev(idx(), pos());
920 }
921
922
923 char MathCursor::valign() const
924 {
925         idx_type idx;
926         MathGridInset * p = enclosingGrid(idx);
927         return p ? p->valign() : '\0';
928 }
929
930
931 char MathCursor::halign() const
932 {
933         idx_type idx;
934         MathGridInset * p = enclosingGrid(idx);
935         return p ? p->halign(idx % p->ncols()) : '\0';
936 }
937
938
939 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
940 {
941         MathCursorPos anc = normalAnchor();
942         if (anc < cursor()) {
943                 i1 = anc;
944                 i2 = cursor();
945         } else {
946                 i1 = cursor();
947                 i2 = anc;
948         }
949 }
950
951
952 MathCursorPos & MathCursor::cursor()
953 {
954         lyx::Assert(depth());
955         return Cursor_.back();
956 }
957
958
959 MathCursorPos const & MathCursor::cursor() const
960 {
961         lyx::Assert(depth());
962         return Cursor_.back();
963 }
964
965
966 bool MathCursor::goUpDown(bool up)
967 {
968         // Be warned: The 'logic' implemented in this function is highly fragile.
969         // A distance of one pixel or a '<' vs '<=' _really_ matters.
970         // So fiddle around with it only if you know what you are doing!
971   int xo = 0;
972         int yo = 0;
973         getPos(xo, yo);
974
975         // check if we had something else in mind, if not, this is the future goal
976         if (targetx_ == -1)
977                 targetx_ = xo;
978         else
979                 xo = targetx_;
980
981         // try neigbouring script insets
982         // try left
983         if (hasPrevAtom()) {
984                 MathScriptInset const * p = prevAtom()->asScriptInset();
985                 if (p && p->has(up)) {
986                         --pos();
987                         push(nextAtom());
988                         idx() = up; // the superscript has index 1
989                         pos() = size();
990                         ///lyxerr << "updown: handled by scriptinset to the left\n";
991                         return true;
992                 }
993         }
994
995         // try right
996         if (hasNextAtom()) {
997                 MathScriptInset const * p = nextAtom()->asScriptInset();
998                 if (p && p->has(up)) {
999                         push(nextAtom());
1000                         idx() = up;
1001                         pos() = 0;
1002                         ///lyxerr << "updown: handled by scriptinset to the right\n";
1003                         return true;
1004                 }
1005         }
1006
1007         // try current cell
1008         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1009         //if (up)
1010         //      yhigh = yo - 4;
1011         //else
1012         //      ylow = yo + 4;
1013         //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1014         //      lyxerr << "updown: handled by brute find in the same cell\n";
1015         //      return true;
1016         //}
1017
1018         // try to find an inset that knows better then we
1019         while (1) {
1020                 ///lyxerr << "updown: We are in " << *par() << " idx: " << idx() << '\n';
1021                 // ask inset first
1022                 if (par()->idxUpDown(idx(), pos(), up, targetx_))
1023                         return true;
1024
1025                 // no such inset found, just take something "above"
1026                 ///lyxerr << "updown: handled by strange case\n";
1027                 if (!popLeft())
1028                         return
1029                                 bruteFind(xo, yo,
1030                                         formula()->xlow(),
1031                                         formula()->xhigh(),
1032                                         up ? formula()->ylow() : yo + 4,
1033                                         up ? yo - 4 : formula()->yhigh()
1034                                 );
1035
1036                 // any improvement so far?
1037                 int xnew, ynew;
1038                 getPos(xnew, ynew);
1039                 if (up ? ynew < yo : ynew > yo)
1040                         return true;
1041         }
1042 }
1043
1044
1045 bool MathCursor::bruteFind
1046         (int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1047 {
1048         MathIterator best_cursor;
1049         double best_dist = 1e10;
1050
1051         MathIterator it = ibegin(formula()->par().nucleus());
1052         MathIterator et = iend(formula()->par().nucleus());
1053         while (1) {
1054                 // avoid invalid nesting when selecting
1055                 if (!selection_ || positionable(it, Anchor_)) {
1056                         int xo, yo;
1057                         it.back().getPos(xo, yo);
1058                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
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                                 if (d <= best_dist) {
1063                                         best_dist   = d;
1064                                         best_cursor = it;
1065                                 }
1066                         }
1067                 }
1068
1069                 if (it == et)
1070                         break;
1071                 ++it;
1072         }
1073
1074         if (best_dist < 1e10)
1075                 Cursor_ = best_cursor;
1076         return best_dist < 1e10;
1077 }
1078
1079
1080 bool MathCursor::idxLineFirst()
1081 {
1082         idx() -= idx() % par()->ncols();
1083         pos() = 0;
1084         return true;
1085 }
1086
1087
1088 bool MathCursor::idxLineLast()
1089 {
1090         idx() -= idx() % par()->ncols();
1091         idx() += par()->ncols() - 1;
1092         pos() = size();
1093         return true;
1094 }
1095
1096 bool MathCursor::idxLeft()
1097 {
1098         return par()->idxLeft(idx(), pos());
1099 }
1100
1101
1102 bool MathCursor::idxRight()
1103 {
1104         return par()->idxRight(idx(), pos());
1105 }
1106
1107
1108 bool MathCursor::interpret(string const & s)
1109 {
1110         //lyxerr << "interpret 1: '" << s << "'\n";
1111         if (s.empty())
1112                 return true;
1113
1114         //lyxerr << "char: '" << s[0] << "'  int: " << int(s[0]) << endl;
1115         //owner_->getIntl()->getTransManager().TranslateAndInsert(s[0], lt);
1116         //lyxerr << "trans: '" << s[0] << "'  int: " << int(s[0]) << endl;
1117
1118         if (s.size() >= 6 && s.substr(0, 6) == "matrix") {
1119                 unsigned int m = 1;
1120                 unsigned int n = 1;
1121                 string v_align;
1122                 string h_align;
1123                 istringstream is(s.substr(6).c_str());
1124                 is >> m >> n >> v_align >> h_align;
1125                 m = max(1u, m);
1126                 n = max(1u, n);
1127                 v_align += 'c';
1128                 niceInsert(MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
1129                 return true;
1130         }
1131
1132         if (s.size() >= 7 && s.substr(0, 7) == "replace") {
1133                 ReplaceData rep;
1134                 istringstream is(s.substr(7).c_str());
1135                 string from, to;
1136                 is >> from >> to;
1137                 mathed_parse_cell(rep.from, from);
1138                 mathed_parse_cell(rep.to, to);
1139                 lyxerr << "replacing '" << from << "' with '" << to << "'\n";
1140                 par()->replace(rep);
1141                 return true;
1142         }
1143
1144         string name = s.substr(1);
1145
1146         if (name == "over" || name == "choose" || name == "atop") {
1147                 MathAtom t(createMathInset(name));
1148                 t.nucleus()->asNestInset()->cell(0) = array();
1149                 array().clear();
1150                 pos() = 0;
1151                 niceInsert(t);
1152                 popRight();
1153                 left();
1154                 return true;
1155         }
1156
1157         // prevent entering of recursive macros
1158         if (formula()->lyxCode() == Inset::MATHMACRO_CODE
1159                 && formula()->getInsetName() == name)
1160         {
1161                 lyxerr << "can't enter recursive macro\n";
1162                 return true;
1163         }
1164
1165         niceInsert(createMathInset(name));
1166         return true;
1167 }
1168
1169
1170 bool MathCursor::script(bool up)
1171 {
1172         // Hack to get \\^ and \\_ working
1173         if (inMacroMode() && macroName() == "\\") {
1174                 if (up)
1175                         interpret("\\mathcircumflex");
1176                 else
1177                         interpret('_');
1178                 return true;
1179         }
1180
1181         macroModeClose();
1182         MathGridInset safe = grabAndEraseSelection();
1183         if (inNucleus()) {
1184                 // we are in a nucleus of a script inset, move to _our_ script
1185                 par()->asScriptInset()->ensure(up);
1186                 idx() = up;
1187                 pos() = 0;
1188         } else if (hasPrevAtom() && prevAtom()->asScriptInset()) {
1189                 prevAtom().nucleus()->asScriptInset()->ensure(up);
1190                 pushRight(prevAtom());
1191                 idx() = up;
1192                 pos() = size();
1193         } else if (hasPrevAtom()) {
1194                 --pos();
1195                 array()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1196                 pushLeft(nextAtom());
1197                 idx() = up;
1198                 pos() = 0;
1199         } else {
1200                 plainInsert(MathAtom(new MathScriptInset(up)));
1201                 prevAtom().nucleus()->asScriptInset()->ensure(up);
1202                 pushRight(prevAtom());
1203                 idx() = up;
1204                 pos() = 0;
1205         }
1206         paste(safe);
1207         dump("1");
1208         return true;
1209 }
1210
1211
1212 bool MathCursor::interpret(char c)
1213 {
1214         //lyxerr << "interpret 2: '" << c << "'\n";
1215         targetx_ = -1; // "no target"
1216         if (inMacroArgMode()) {
1217                 --pos();
1218                 plainErase();
1219                 int n = c - '0';
1220                 MathMacroTemplate const * p = formula()->par()->asMacroTemplate();
1221                 if (p && 1 <= n && n <= p->numargs())
1222                         insert(MathAtom(new MathMacroArgument(c - '0')));
1223                 else {
1224                         insert(createMathInset("#"));
1225                         interpret(c); // try again
1226                 }
1227                 return true;
1228         }
1229
1230         // handle macroMode
1231         if (inMacroMode()) {
1232                 string name = macroName();
1233                 //lyxerr << "interpret name: '" << name << "'\n";
1234
1235                 if (name.empty() && c == '\\') {
1236                         backspace();
1237                         interpret("\\backslash");
1238                         return true;
1239                 }
1240
1241                 if (isalpha(c)) {
1242                         activeMacro()->setName(activeMacro()->name() + c);
1243                         return true;
1244                 }
1245
1246                 // handle 'special char' macros
1247                 if (name == "\\") {
1248                         // remove the '\\'
1249                         backspace();
1250                         if (c == '\\')
1251                                 interpret("\\backslash");
1252                         else
1253                                 interpret(string("\\") + c);
1254                         return true;
1255                 }
1256
1257                 // leave macro mode and try again if necessary
1258                 macroModeClose();
1259                 if (c != ' ')
1260                         interpret(c);
1261                 return true;
1262         }
1263
1264         // This is annoying as one has to press <space> far too often.
1265         // Disable it.
1266
1267         if (0) {
1268                 // leave autocorrect mode if necessary
1269                 if (autocorrect_ && c == ' ') {
1270                         autocorrect_ = false;
1271                         return true;
1272                 }
1273         }
1274
1275         // just clear selection on pressing the space bar
1276         if (selection_ && c == ' ') {
1277                 selection_ = false;
1278                 return true;
1279         }
1280
1281         selClearOrDel();
1282
1283         if (c == '\\') {
1284                 //lyxerr << "starting with macro\n";
1285                 insert(MathAtom(new MathUnknownInset("\\", false)));
1286                 return true;
1287         }
1288
1289         if (c == '\n') {
1290                 if (currentMode() == MathInset::TEXT_MODE) 
1291                         insert(c);
1292                 return true;
1293         }
1294
1295         if (c == ' ') {
1296                 if (currentMode() == MathInset::TEXT_MODE) {
1297                         // insert spaces in text mode,
1298                         // but suppress direct insertion of two spaces in a row
1299                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1300                         // it is better than nothing...
1301                         if (!hasPrevAtom() || prevAtom()->getChar() != ' ')
1302                                 insert(c);
1303                         return true;
1304                 }
1305                 if (hasPrevAtom() && prevAtom()->asSpaceInset()) {
1306                         prevAtom().nucleus()->asSpaceInset()->incSpace();
1307                         return true;
1308                 }
1309                 if (popRight())
1310                         return true;
1311                 // if are at the very end, leave the formula
1312                 return pos() != size();
1313         }
1314
1315         if (c == '#') {
1316                 insert(c); // LM_TC_TEX;
1317                 return true;
1318         }
1319
1320 /*
1321         if (c == '{' || c == '}', c)) {
1322                 insert(c); // LM_TC_TEX;
1323                 return true;
1324         }
1325 */
1326
1327         if (c == '{') {
1328                 niceInsert(MathAtom(new MathBraceInset));
1329                 return true;
1330         }
1331
1332         if (c == '}') {
1333                 return true;
1334         }
1335
1336         if (c == '$') {
1337                 insert(createMathInset("$"));
1338                 return true;
1339         }
1340
1341         if (c == '%') {
1342                 niceInsert(MathAtom(new MathCommentInset));
1343                 return true;
1344         }
1345
1346 /*
1347         if (isalpha(c) && lastcode_ == LM_TC_GREEK) {
1348                 insert(c, LM_TC_VAR);
1349                 return true;
1350         }
1351
1352         if (isalpha(c) && lastcode_ == LM_TC_GREEK1) {
1353                 insert(c, LM_TC_VAR);
1354                 lastcode_ = LM_TC_VAR;
1355                 return true;
1356         }
1357
1358         if (c == '\\') {
1359                 insert(c, LM_TC_TEX);
1360                 //bv->owner()->message(_("TeX mode"));
1361                 return true;
1362         }
1363 */
1364
1365         // try auto-correction
1366         //if (autocorrect_ && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1367         //      return true;
1368
1369         // no special circumstances, so insert the character without any fuss
1370         insert(c);
1371         autocorrect_ = true;
1372         return true;
1373 }
1374
1375
1376 void MathCursor::setSelection(MathIterator const & where, size_type n)
1377 {
1378         selection_ = true;
1379         Anchor_ = where;
1380         Cursor_ = where;
1381         cursor().pos_ += n;
1382 }
1383
1384
1385 void MathCursor::insetToggle()
1386 {
1387         if (hasNextAtom()) {
1388                 // toggle previous inset ...
1389                 nextAtom().nucleus()->lock(!nextAtom()->lock());
1390         } else if (popLeft() && hasNextAtom()) {
1391                 // ... or enclosing inset if we are in the last inset position
1392                 nextAtom().nucleus()->lock(!nextAtom()->lock());
1393                 posRight();
1394         }
1395 }
1396
1397
1398 string MathCursor::info() const
1399 {
1400         ostringstream os;
1401         os << "Math editor mode.  ";
1402         for (int i = 0, n = depth(); i < n; ++i) {
1403                 Cursor_[i].par_->infoize(os);
1404                 os << "  ";
1405         }
1406         if (hasPrevAtom())
1407                 if (prevAtom()->asSymbolInset() || prevAtom()->asScriptInset())
1408                         prevAtom()->infoize(os);
1409         os << "                    ";
1410         return os.str().c_str(); // .c_str() needed for lyxstring
1411 }
1412
1413
1414 unsigned MathCursor::depth() const
1415 {
1416         return Cursor_.size();
1417 }
1418
1419
1420
1421
1422 namespace {
1423
1424 void region(MathCursorPos const & i1, MathCursorPos const & i2,
1425         MathInset::row_type & r1, MathInset::row_type & r2,
1426         MathInset::col_type & c1, MathInset::col_type & c2)
1427 {
1428         MathInset * p = i1.par_;
1429         c1 = p->col(i1.idx_);
1430         c2 = p->col(i2.idx_);
1431         if (c1 > c2)
1432                 swap(c1, c2);
1433         r1 = p->row(i1.idx_);
1434         r2 = p->row(i2.idx_);
1435         if (r1 > r2)
1436                 swap(r1, r2);
1437 }
1438
1439 }
1440
1441
1442 MathGridInset MathCursor::grabSelection() const
1443 {
1444         if (!selection_)
1445                 return MathGridInset();
1446         MathCursorPos i1;
1447         MathCursorPos i2;
1448         getSelection(i1, i2);
1449         // shouldn't we assert on i1.par_ == i2.par_?
1450         if (i1.idx_ == i2.idx_) {
1451                 MathGridInset data(1, 1);
1452                 MathArray::const_iterator it = i1.cell().begin();
1453                 data.cell(0) = MathArray(it + i1.pos_, it + i2.pos_);
1454                 return data;
1455         }
1456         row_type r1, r2;
1457         col_type c1, c2;
1458         region(i1, i2, r1, r2, c1, c2);
1459         MathGridInset data(c2 - c1 + 1, r2 - r1 + 1);
1460         for (row_type row = 0; row < data.nrows(); ++row)
1461                 for (col_type col = 0; col < data.ncols(); ++col) {
1462                         idx_type i = i1.par_->index(row + r1, col + c1);
1463                         data.cell(data.index(row, col)) = i1.par_->cell(i);
1464                 }
1465         return data;
1466 }
1467
1468
1469 void MathCursor::eraseSelection()
1470 {
1471         MathCursorPos i1;
1472         MathCursorPos i2;
1473         getSelection(i1, i2);
1474         if (i1.idx_ == i2.idx_)
1475                 i1.cell().erase(i1.pos_, i2.pos_);
1476         else {
1477                 MathInset * p = i1.par_;
1478                 row_type r1, r2;
1479                 col_type c1, c2;
1480                 region(i1, i2, r1, r2, c1, c2);
1481                 for (row_type row = r1; row <= r2; ++row)
1482                         for (col_type col = c1; col <= c2; ++col)
1483                                 p->cell(p->index(row, col)).clear();
1484         }
1485         cursor() = i1;
1486 }
1487
1488
1489 MathGridInset MathCursor::grabAndEraseSelection()
1490 {
1491         if (!selection_)
1492                 return MathGridInset();
1493         MathGridInset res = grabSelection();
1494         eraseSelection();
1495         selection_ = false;
1496         return res;
1497 }
1498
1499
1500 MathCursorPos MathCursor::normalAnchor() const
1501 {
1502         if (Anchor_.size() < depth()) {
1503                 Anchor_ = Cursor_;
1504                 lyxerr << "unusual Anchor size\n";
1505         }
1506         //lyx::Assert(Anchor_.size() >= cursor.depth());
1507         // use Anchor on the same level as Cursor
1508         MathCursorPos normal = Anchor_[depth() - 1];
1509         if (depth() < Anchor_.size() && !(normal < cursor())) {
1510                 // anchor is behind cursor -> move anchor behind the inset
1511                 ++normal.pos_;
1512         }
1513         return normal;
1514 }
1515
1516
1517
1518 void MathCursor::handleExtern(const string & arg)
1519 {
1520         string lang;
1521         string extra;
1522         istringstream iss(arg.c_str());
1523         iss >> lang >> extra;
1524         if (extra.empty())
1525                 extra = "noextra";
1526
1527         if (selection()) {
1528                 MathArray ar;
1529                 selGet(ar);
1530                 lyxerr << "use selection: " << ar << "\n";
1531                 insert(pipeThroughExtern(lang, extra, ar));
1532                 return;
1533         }
1534
1535         MathArray eq;
1536         eq.push_back(MathAtom(new MathCharInset('=')));
1537
1538         popToEnclosingHull();
1539
1540         idx_type idx = 0;
1541         MathHullInset * hull = enclosingHull(idx);
1542         lyx::Assert(hull);
1543         idxLineFirst();
1544
1545         if (hull->getType() == "simple") {
1546                 MathArray::size_type pos = cursor().cell().find_last(eq);
1547                 MathArray ar;
1548                 if (pos == size()) {
1549                         ar = array();
1550                         lyxerr << "use whole cell: " << ar << "\n";
1551                 } else {
1552                         ar = MathArray(array().begin() + pos + 1, array().end());
1553                         lyxerr << "use partial cell form pos: " << pos << "\n";
1554                 }
1555                 end();
1556                 insert(eq);
1557                 insert(pipeThroughExtern(lang, extra, ar));
1558                 return;
1559         }
1560
1561         if (hull->getType() == "equation") {
1562                 lyxerr << "use equation inset\n";
1563                 hull->mutate("eqnarray");
1564                 MathArray & ar = cursor().cell();
1565                 lyxerr << "use cell: " << ar << "\n";
1566                 idxRight();
1567                 cursor().cell() = eq;
1568                 idxRight();
1569                 cursor().cell() = pipeThroughExtern(lang, extra, ar);
1570                 idxLineLast();
1571                 return;
1572         }
1573
1574         {
1575                 lyxerr << "use eqnarray\n";
1576                 idxLineLast();
1577                 MathArray ar = cursor().cell();
1578                 lyxerr << "use cell: " << ar << "\n";
1579 #ifdef WITH_WARNINGS
1580 #warning temporarily disabled
1581 #endif
1582                 //breakLine();
1583                 //idxRight();
1584                 cursor().cell() = eq;
1585                 //idxRight();
1586                 cursor().cell() = pipeThroughExtern(lang, extra, ar);
1587                 idxLineLast();
1588         }
1589
1590 }
1591
1592
1593 MathInset::result_type MathCursor::dispatch(FuncRequest const & cmd)
1594 {
1595         // try to dispatch to adajcent items if they are not editable
1596         // actually, this should only happen for mouse clicks...
1597         idx_type d1;
1598         pos_type d2;
1599         if (hasNextAtom() && !openable(nextAtom(), false)) {
1600                 MathInset::result_type res = nextAtom().nucleus()->dispatch(cmd, d1, d2);
1601                 if (res != MathInset::UNDISPATCHED)
1602                         return res;
1603         }
1604         if (hasPrevAtom() && !openable(prevAtom(), false)) {
1605                 MathInset::result_type res = prevAtom().nucleus()->dispatch(cmd, d1, d2);
1606                 if (res != MathInset::UNDISPATCHED)
1607                         return res;
1608         }
1609
1610         for (int i = Cursor_.size() - 1; i >= 0; --i) {
1611                 MathCursorPos & pos = Cursor_[i];
1612                 MathInset::result_type const res
1613                         = pos.par_->dispatch(cmd, pos.idx_, pos.pos_);
1614                 if (res != MathInset::UNDISPATCHED) {
1615                         if (res == MathInset::DISPATCHED_POP) {
1616                                 Cursor_.shrink(i + 1);
1617                                 selClear();
1618                         }
1619                         return res;
1620                 }
1621         }
1622         return MathInset::UNDISPATCHED;
1623 }
1624
1625
1626 MathInset::mode_type MathCursor::currentMode() const
1627 {
1628         for (int i = Cursor_.size() - 1; i >= 0; --i) {
1629                 MathInset::mode_type res = Cursor_[i].par_->currentMode();
1630                 if (res != MathInset::UNDECIDED_MODE)
1631                         return res;
1632         }
1633         return MathInset::UNDECIDED_MODE;
1634 }
1635
1636
1637 void releaseMathCursor(BufferView * bv)
1638 {
1639         if (!mathcursor)
1640                 return;
1641         mathcursor->formula()->hideInsetCursor(bv);
1642         delete mathcursor;
1643         mathcursor = 0;
1644 }