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