]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
mathed108.diff
[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 #ifdef __GNUG__
19 #pragma implementation
20 #endif
21
22 #include <config.h>
23 #include <algorithm>
24 #include <cctype>
25
26 #include "debug.h"
27 #include "LColor.h"
28 #include "Painter.h"
29 #include "mathed/support.h"
30 #include "formulabase.h"
31 #include "math_cursor.h"
32 #include "math_arrayinset.h"
33 #include "math_bigopinset.h"
34 #include "math_decorationinset.h"
35 #include "math_deliminset.h"
36 #include "math_dotsinset.h"
37 #include "math_fracinset.h"
38 #include "math_funcinset.h"
39 #include "math_gridinset.h"
40 #include "math_macro.h"
41 #include "math_macroarg.h"
42 #include "math_macrotable.h"
43 #include "math_macrotemplate.h"
44 #include "math_matrixinset.h"
45 #include "math_rootinset.h"
46 #include "math_spaceinset.h"
47 #include "math_sqrtinset.h"
48 #include "support/lstrings.h"
49 #include "math_scriptinset.h"
50 #include "math_parser.h"
51
52 using std::endl;
53 using std::min;
54 using std::max;
55 using std::isalnum;
56
57
58 namespace {
59
60 struct Selection
61 {
62         void grab(MathCursor const & cursor)
63         {
64                 data_.clear();
65                 MathCursorPos i1;
66                 MathCursorPos i2;
67                 cursor.getSelection(i1, i2); 
68                 if (i1.idx_ == i2.idx_)
69                         data_.push_back(MathArray(i1.cell(), i1.pos_, i2.pos_));
70                 else {
71 #ifdef RECTANGULAR_SELECT
72                         std::vector<int> indices = i1.par_->idxBetween(i1.idx_, i2.idx_);
73                         for (unsigned i = 0; i < indices.size(); ++i)
74                                 data_.push_back(i1.cell(indices[i]));
75 #else
76                         data_.push_back(MathArray(i1.cell(), i1.pos_, i1.cell().size()));
77                         for (int i = i1.idx_ + 1; i < i2.idx_; ++i)
78                                 data_.push_back(i1.cell(i));
79                         data_.push_back(MathArray(i2.cell(), 0, i2.pos_));
80 #endif
81                 }
82         }
83
84         void erase(MathCursor & cursor)
85         {
86                 MathCursorPos i1;
87                 MathCursorPos i2;
88                 cursor.getSelection(i1, i2); 
89                 if (i1.idx_ == i2.idx_) {
90                         i1.cell().erase(i1.pos_, i2.pos_);
91                 } else {
92                         std::vector<int> indices = i1.par_->idxBetween(i1.idx_, i2.idx_);
93                         for (unsigned i = 0; i < indices.size(); ++i)
94                                 i1.cell(indices[i]).erase();
95                 }
96                 cursor.cursor() = i1;
97         }
98
99         void paste(MathCursor & cursor) const
100         {
101                 cursor.insert(glue());
102         }
103
104         // glues selection to one cell
105         MathArray glue() const
106         {
107                 MathArray ar;
108                 for (unsigned i = 0; i < data_.size(); ++i)
109                         ar.push_back(data_[i]);
110                 return ar;
111         }
112
113         void clear()
114         {
115                 data_.clear();
116         }
117
118         std::vector<MathArray> data_;
119 };
120
121
122 Selection theSelection;
123
124
125 std::ostream & operator<<(std::ostream & os, MathCursorPos const & p)
126 {
127         os << "(par: " << p.par_ << " idx: " << p.idx_
128            << " pos: " << p.pos_ << ")";
129         return os;
130 }
131
132 }
133
134
135 MathCursor::MathCursor(InsetFormulaBase * formula)
136         : formula_(formula)
137 {
138         lastcode   = LM_TC_MIN;
139         macro_mode = false;
140         selection  = false;
141         first();
142 }
143
144
145 void MathCursor::push(MathInset * par, bool first)
146 {
147         MathCursorPos p;
148         p.par_ = par;
149         if (first)
150                 par->idxFirst(p.idx_, p.pos_);
151         else
152                 par->idxLast(p.idx_, p.pos_);
153         Cursor_.push_back(p);
154 }
155
156
157 bool MathCursor::pop()
158 {
159         if (Cursor_.size() <= 1)
160                 return false;
161         Cursor_.pop_back();
162         return true;
163 }
164
165
166 MathInset * MathCursor::parInset(int i) const
167 {
168         return Cursor_[i].par_;
169 }
170
171
172 void MathCursor::dump(char const * what) const
173 {
174         return;
175
176         lyxerr << "MC: " << what << "\n";
177         for (unsigned i = 0; i < Cursor_.size(); ++i)
178                 lyxerr << "  i: " << i 
179                         << " pos: " << Cursor_[i].pos_
180                         << " idx: " << Cursor_[i].idx_
181                         << " par: " << Cursor_[i].par_ << "\n";
182
183         //lyxerr        << " sel: " << selection << " data: " << array() << "\n";
184 }
185
186
187 void MathCursor::seldump(char const *) const
188 {
189         //lyxerr << "SEL: " << str << ": '" << theSelection << "'\n";
190         //dump("   Pos");
191         return;
192
193         //lyxerr << "\n\n\\n=================vvvvvvvvvvvvv=======================   "
194         //      <<  str << "\ntheSelection: " << theSelection;
195         //for (unsigned int i = 0; i < Cursor_.size(); ++i) 
196         //      lyxerr << Cursor_[i].par_ << "\n'" << Cursor_[i].cell() << "'\n";
197         //lyxerr << "\ncursor.pos_: " << cursor().pos_;
198         //lyxerr << "\nanchor.pos_: " << anchor().pos_;
199         //lyxerr << "\n===================^^^^^^^^^^^^=====================\n\n\n";
200 }
201
202
203 bool MathCursor::isInside(MathInset * p) const
204 {
205         for (unsigned i = 0; i < Cursor_.size(); ++i) 
206                 if (parInset(i) == p) 
207                         return true;
208         return false;
209 }
210
211
212 bool MathCursor::openable(MathInset * p, bool sel, bool useupdown) const
213 {
214         if (!p)
215                 return false;
216         if (!(p->isActive() || (useupdown && p->isScriptInset())))
217                 return false;
218
219         if (sel) {
220                 // we can't move into anything new during selection
221                 if (Cursor_.size() == Anchor_.size())
222                         return false;
223                 if (p != Anchor_[Cursor_.size()].par_)
224                         return false;
225         }
226         return true;
227 }
228
229
230 bool MathCursor::plainLeft()
231 {
232         return array().prev(cursor().pos_);
233 }
234
235
236 bool MathCursor::Left(bool sel)
237 {
238         dump("Left 1");
239         if (macro_mode) {
240                 // was MacroModeBack()
241                 if (!imacro->name().empty()) {
242                         imacro->SetName(imacro->name().substr(0, imacro->name().length()-1));
243                         imacro->Metrics(imacro->size());
244                 } else
245                         MacroModeClose();
246                 return true;
247         }
248         SelHandle(sel);
249         clearLastCode();
250
251         MathInset * p = prevInset();
252         if (openable(p, sel, false)) {
253                 plainLeft();
254                 push(p, false);
255                 return true;
256         } 
257         if (plainLeft())
258                 return true;
259         if (cursor().par_->idxLeft(cursor().idx_, cursor().pos_))
260                 return true;
261         if (pop())
262                 return true;
263         return false;
264 }
265
266
267 bool MathCursor::plainRight()
268 {
269         return array().next(cursor().pos_);
270 }
271
272
273 bool MathCursor::Right(bool sel)
274 {
275         dump("Right 1");
276         if (macro_mode) {
277                 MacroModeClose();
278                 return true;
279         }
280         SelHandle(sel);
281         clearLastCode();
282
283         MathInset * p = nextInset();
284         if (openable(p, sel, false)) {
285                 push(p, true);
286                 return true;
287         }
288         if (array().next(cursor().pos_))
289                 return true;
290         if (cursor().par_->idxRight(cursor().idx_, cursor().pos_))
291                 return true;
292         if (!pop())
293                 return false;
294         array().next(cursor().pos_);
295         return true;
296 }
297
298
299 void MathCursor::first()
300 {
301         Cursor_.clear();
302         push(formula_->par(), true);
303 }
304
305
306 void MathCursor::last()
307 {
308         Cursor_.clear();
309         push(formula_->par(), false);
310 }
311
312
313 void MathCursor::SetPos(int x, int y)
314 {
315         dump("SetPos 1");
316         //lyxerr << "MathCursor::SetPos x: " << x << " y: " << y << "\n";
317
318         MacroModeClose();
319         lastcode = LM_TC_MIN;
320         first();
321
322         cursor().par_  = formula()->par();
323
324         while (1) {
325                 cursor().idx_ = -1;
326                 cursor().pos_ = -1;
327                 //lyxerr << "found idx: " << idx_ << " cursor: " << cursor().pos_  << "\n";
328                 int distmin = 1 << 30; // large enough
329                 for (int i = 0; i < cursor().par_->nargs(); ++i) {
330                         MathXArray const & ar = cursor().par_->xcell(i);
331                         int x1 = x - ar.xo();
332                         int y1 = y - ar.yo();
333                         int c  = ar.x2pos(x1);
334                         int xx = abs(x1 - ar.pos2x(c));
335                         int yy = abs(y1);
336                         //lyxerr << "idx: " << i << " xx: " << xx << " yy: " << yy
337                         //      << " c: " << c  << " xo: " << ar.xo() << "\n";
338                         if (yy + xx <= distmin) {
339                                 distmin        = yy + xx;
340                                 cursor().idx_  = i;
341                                 cursor().pos_  = c;
342                         }
343                 }
344                 //lyxerr << "found idx: " << cursor().idx_ << " cursor: "
345                 //      << cursor().pos_  << "\n";
346                 MathInset * n = nextInset();
347                 MathInset * p = prevInset();
348                 if (openable(n, selection, true) && n->covers(x, y))
349                         push(n, true);
350                 else if (openable(p, selection, true) && p->covers(x, y)) {
351                         plainLeft();
352                         push(p, false);
353                 } else 
354                         break;
355         }
356         dump("SetPos 2");
357 }
358
359
360 void MathCursor::Home()
361 {
362         dump("Home 1");
363         MacroModeClose();
364         clearLastCode();
365         if (!cursor().par_->idxHome(cursor().idx_, cursor().pos_)) 
366                 pop();
367         dump("Home 2");
368 }
369
370
371 void MathCursor::End()
372 {
373         dump("End 1");
374         MacroModeClose();
375         clearLastCode();
376         if (!cursor().par_->idxEnd(cursor().idx_, cursor().pos_)) {
377                 pop();
378                 array().next(cursor().pos_);
379         }
380         dump("End 2");
381 }
382
383
384 void MathCursor::erase()
385 {
386         array().erase(cursor().pos_);
387 }
388
389
390 void MathCursor::insert(char c, MathTextCodes t)
391 {
392         //lyxerr << "inserting '" << c << "'\n";
393         if (selection)
394                 SelDel();
395
396         if (t == LM_TC_MIN)
397                 t = lastcode;
398
399         if (macro_mode && !(MathIsAlphaFont(t) || t == LM_TC_MIN))
400                 MacroModeClose();
401
402         if (macro_mode) {
403                 if (MathIsAlphaFont(t) || t == LM_TC_MIN) {
404                         // was MacroModeinsert(c);
405                         imacro->SetName(imacro->name() + static_cast<char>(c));
406                         return;
407                 }
408         }
409
410         array().insert(cursor().pos_, c, t);
411         array().next(cursor().pos_);
412
413         lastcode = t;
414 }
415
416
417 void MathCursor::insert(MathInset * p)
418 {
419         MacroModeClose();
420
421         if (selection) {
422                 if (p->nargs())
423                         SelCut();
424                 else
425                         SelDel();
426         }
427
428         array().insert(cursor().pos_, p);
429         array().next(cursor().pos_);
430 }
431
432
433 void MathCursor::insert(MathArray const & ar)
434 {
435         MacroModeClose();
436         if (selection)
437                 SelCut();
438
439         array().insert(cursor().pos_, ar);
440         cursor().pos_ += ar.size();
441 }
442
443
444 void MathCursor::Delete()
445 {
446         dump("Delete 1");
447         if (macro_mode)
448                 return;
449
450         if (selection) {
451                 SelDel();
452                 return;
453         }
454
455         // delete empty cells if necessary
456         if (cursor().pos_ == 0 && array().size() == 0) {
457                 bool popit;
458                 bool removeit;
459                 cursor().par_->idxDelete(cursor().idx_, popit, removeit);
460                 if (popit && pop() && removeit)
461                         Delete();
462                 return;
463         }
464
465         if (cursor().pos_ < array().size())
466                 array().erase(cursor().pos_);
467
468         dump("Delete 2");
469 }
470
471
472 void MathCursor::DelLine()
473 {
474         MacroModeClose();
475
476         if (selection) {
477                 SelDel();
478                 return;
479         }
480
481         if (cursor().par_->nrows() > 1)
482                 cursor().par_->delRow(row());
483 }
484
485
486 bool MathCursor::Up(bool sel)
487 {
488         dump("Up 1");
489         MacroModeClose();
490         SelHandle(sel);
491
492         if (selection) {
493                 int x = xarray().pos2x(cursor().pos_);
494                 if (cursor().idxDown()) {
495                         cursor().pos_ = xarray().x2pos(x);
496                         return true;
497                 }
498                 if (pop()) 
499                         return true;
500                 return false;
501         }
502
503         // check whether we could move into an inset on the right or on the left
504         MathInset * p = nextInset();
505         if (p) {
506                 int idx, pos;
507                 if (p->idxFirstUp(idx, pos)) {
508                         push(p, true);
509                         cursor().idx_ = idx;
510                         cursor().pos_ = pos;
511                         dump("Up 3");
512                         return true;
513                 }
514         }
515
516         p = prevInset();
517         if (p) {
518                 int idx, pos;
519                 if (p->idxLastUp(idx, pos)) {
520                         plainLeft();
521                         push(p, false);
522                         cursor().idx_ = idx;
523                         cursor().pos_ = pos;
524                         dump("Up 4");
525                         return true;
526                 }
527         }
528
529         int x = xarray().pos2x(cursor().pos_);
530         if (cursor().idxUp()) {
531                 cursor().pos_ = xarray().x2pos(x);
532                 return true;
533         }
534         if (pop())
535                 return true;
536         return false;
537 }
538
539
540 bool MathCursor::Down(bool sel)
541 {
542         dump("Down 1");
543         MacroModeClose();
544         SelHandle(sel);
545
546         if (selection) {
547                 int x = xarray().pos2x(cursor().pos_);
548                 if (cursor().idxDown()) {
549                         cursor().pos_ = xarray().x2pos(x);
550                         return true;
551                 }
552                 if (pop()) 
553                         return true;
554                 return false;
555         }
556
557         // check whether we could move into an inset on the right or on the left
558         MathInset * p = nextInset();
559         if (p) {
560                 int idx, pos;
561                 if (p->idxFirstDown(idx, pos)) {
562                         push(p, true);
563                         cursor().idx_ = idx;
564                         cursor().pos_ = pos;
565                         dump("Down 3");
566                         return true;
567                 }
568         }
569
570         p = prevInset();
571         if (p) {
572                 int idx, pos;
573                 if (p->idxLastDown(idx, pos)) {
574                         plainLeft();
575                         push(p, false);
576                         cursor().idx_ = idx;
577                         cursor().pos_ = pos;
578                         dump("Down 4");
579                         return true;
580                 }
581         }
582
583         int x = xarray().pos2x(cursor().pos_);
584         if (cursor().idxDown()) {
585                 cursor().pos_ = xarray().x2pos(x);
586                 return true;
587         }
588         if (pop())
589                 return true;
590         return false;
591 }
592
593
594 bool MathCursor::toggleLimits()
595 {
596         if (!prevIsInset())
597                 return false;
598         MathInset * p = prevInset();
599         int old = p->limits();
600         p->limits(old < 0 ? 1 : -1);
601         return old != p->limits();
602 }
603
604
605 void MathCursor::SetSize(MathStyles size)
606 {
607         cursor().par_->UserSetSize(size);
608 }
609
610
611
612 void MathCursor::Interpret(string const & s)
613 {
614         //lyxerr << "Interpret: '" << s << "'\n";
615         //lyxerr << "in: " << in_word_set(s) << " \n";
616
617         if (s.size() && (s[0] == '^' || s[0] == '_')) {
618                 bool const up = (s[0] == '^');
619                 SelCut();       
620                 MathScriptInset * p = prevScriptInset();
621                 if (!p) {
622                         MathInset * b = prevInset();
623                         if (b && b->isScriptable()) {
624                                 p = new MathScriptInset(up, !up, b->clone());
625                                 plainLeft();
626                                 erase();
627                         } else {
628                                 p = new MathScriptInset(up, !up);
629                         }
630                         insert(p);
631                         plainLeft();
632                 }
633                 push(p, true);
634                 if (up)
635                         p->up(true);
636                 else
637                         p->down(true);
638                 cursor().idx_ = up ? 0 : 1;
639                 cursor().pos_ = 0;
640                 SelPaste();
641                 return;
642         }
643
644         if (s[0] == '!' || s[0] == ','  || s[0] == ':' || s[0] == ';') {
645                 int sp = (s[0] == ',') ? 1:((s[0] == ':') ? 2:((s[0] == ';') ? 3: 0));
646                 insert(new MathSpaceInset(sp));
647                 return;
648         }
649
650         MathInset * p = 0;
651         latexkeys const * l = in_word_set(s);
652
653         if (l == 0) {
654                 if (s == "root") 
655                         p = new MathRootInset;
656                 else if (MathMacroTable::hasTemplate(s))
657                         p = new MathMacro(MathMacroTable::provideTemplate(s));
658                 else if (s.size() > 7 && s.substr(0, 7) == "matrix ") {
659                         int m = 1;
660                         int n = 1;
661                         string v_align;
662                         string h_align;
663                         istringstream is(s.substr(7).c_str());
664                         is >> m >> n >> v_align >> h_align;
665                         m = std::max(1, m);
666                         n = std::max(1, n);
667                         v_align += 'c';
668                         MathArrayInset * pp = new MathArrayInset(m, n);
669                         pp->valign(v_align[0]);
670                         pp->halign(h_align);
671                         p = pp;
672                 }
673                 else
674                         p = new MathFuncInset(s, LM_OT_UNDEF);
675         } else {
676                 switch (l->token) {
677                         case LM_TK_BIGSYM: 
678                                 p = new MathBigopInset(s, l->id);
679                                 break;
680                                 
681                         case LM_TK_SYM: {
682                                 MathTextCodes code = static_cast<MathTextCodes>(l->id);
683                                 if (code < 255)
684                                         insert(l->id, MathIsBOPS(code) ? LM_TC_BOPS : LM_TC_SYMB);
685                                 else
686                                         p = new MathFuncInset(l->name);
687                                 break;
688                         }
689
690                         case LM_TK_STACK:
691                                 p = new MathFracInset("stackrel");
692                                 break;
693
694                         case LM_TK_FRAC:
695                                 p = new MathFracInset("frac");
696                                 break;
697
698                         case LM_TK_SQRT:
699                                 p = new MathSqrtInset;
700                                 break;
701
702                         case LM_TK_DECORATION:
703                                 p = new MathDecorationInset(l->name, l->id);
704                                 break;
705
706                         case  LM_TK_FUNCLIM:
707                                 p = new MathFuncInset(l->name, LM_OT_FUNCLIM);
708                                 break;
709
710                         case LM_TK_SPACE:
711                                 p = new MathSpaceInset(l->id);
712                                 break;
713
714                         case LM_TK_DOTS:
715                                 p = new MathDotsInset(l->name, l->id);
716                                 break;
717
718                         case LM_TK_MACRO:
719                                 p = new MathMacro(MathMacroTable::provideTemplate(s));
720                                 break;
721
722                         default:
723                                 p = new MathFuncInset(l->name);
724                                 break;
725                 }
726         }
727
728         if (p) {
729                 bool oldsel = selection;
730                 if (oldsel) 
731                         SelCut();
732                 insert(p);
733                 if (p->nargs()) {
734                         plainLeft();
735                         //push(p, true);
736                         Right();  // do not push for e.g. MathBigopInset
737                         if (oldsel) 
738                                 SelPaste();
739                 }
740                 p->Metrics(p->size());
741         }
742 }
743
744
745 void MathCursor::MacroModeOpen()
746 {
747         if (!macro_mode) {
748                 imacro = new MathFuncInset("");
749                 insert(imacro);
750                 macro_mode = true;
751         } else
752                 lyxerr << "Math Warning: Already in macro mode" << endl;
753 }
754
755
756 void MathCursor::MacroModeClose()
757 {
758         if (macro_mode) {
759                 string name = imacro->name();
760                 plainLeft();
761                 erase();
762                 delete imacro;
763                 macro_mode = false;
764                 imacro = 0;
765                 Interpret(name);
766         }
767 }
768
769
770 void MathCursor::SelCopy()
771 {
772         seldump("SelCopy");
773         if (selection) {
774                 theSelection.grab(*this);
775                 SelClear();
776         }
777 }
778
779
780 void MathCursor::SelCut()
781 {
782         seldump("SelCut");
783         if (selection) {
784                 theSelection.grab(*this);
785                 theSelection.erase(*this);
786                 SelClear();
787         }
788 }
789
790
791 void MathCursor::SelDel()
792 {
793         seldump("SelDel");
794         if (selection) {
795                 theSelection.erase(*this);
796                 SelClear();
797         }
798 }
799
800
801 void MathCursor::SelPaste()
802 {
803         seldump("SelPaste");
804         theSelection.paste(*this);
805         SelClear();
806 }
807
808
809 void MathCursor::SelHandle(bool sel)
810 {
811         if (sel && !selection)
812                 SelStart();
813         if (!sel && selection)
814                 SelClear();
815 }
816
817
818 void MathCursor::SelStart()
819 {
820         seldump("SelStart");
821         if (selection)
822                 return;
823
824         Anchor_ = Cursor_;
825         selection = true;
826 }
827
828
829 void MathCursor::SelClear()
830 {
831         selection = false;
832 }
833
834
835 void MathCursor::drawSelection(Painter & pain) const
836 {
837         if (!selection)
838                 return;
839
840         MathCursorPos i1;
841         MathCursorPos i2;
842         getSelection(i1, i2);
843
844         //lyxerr << "selection from: " << i1 << " to " << i2 << "\n";
845
846         if (i1.idx_ == i2.idx_) {
847                 MathXArray & c = i1.xcell();
848                 int x1 = c.xo() + c.pos2x(i1.pos_);
849                 int y1 = c.yo() - c.ascent();
850                 int x2 = c.xo() + c.pos2x(i2.pos_);
851                 int y2 = c.yo() + c.descent();
852                 pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
853         } else {
854
855                 std::vector<int> indices = i1.par_->idxBetween(i1.idx_, i2.idx_);
856                 for (unsigned i = 0; i < indices.size(); ++i) {
857                         MathXArray & c = i1.xcell(indices[i]);
858                         int x1 = c.xo();
859                         int y1 = c.yo() - c.ascent();
860                         int x2 = c.xo() + c.width();
861                         int y2 = c.yo() + c.descent();
862                         pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
863                 }
864         }
865 }
866
867
868 void MathCursor::handleFont(MathTextCodes t)
869 {
870         if (selection) {
871                 MathCursorPos i1;
872                 MathCursorPos i2;
873                 getSelection(i1, i2); 
874                 if (i1.idx_ == i2.idx_) {
875                         MathArray & ar = i1.cell();
876                         for (int pos = i1.pos_; pos != i2.pos_; ar.next(pos))
877                                 if (!ar.isInset(pos) && isalnum(ar.GetChar(pos))) { 
878                                         MathTextCodes c = ar.GetCode(pos) == t ? LM_TC_VAR : t;
879                                         ar.setCode(pos, c);
880                                 }
881                 }
882         } else {
883                 lastcode = (lastcode == t) ? LM_TC_VAR : t;
884         }
885 }
886
887
888 void MathCursor::handleAccent(string const & name, int code)
889 {
890         MathDecorationInset * p = new MathDecorationInset(name, code);
891         if (selection) {
892                 SelCut();
893                 p->cell(0) = theSelection.glue();
894         }
895         insert(p);
896         push(p, true);
897 }
898
899
900 void MathCursor::handleDelim(int l, int r)
901 {
902         MathDelimInset * p = new MathDelimInset(l, r);
903         if (selection) {
904                 SelCut();
905                 p->cell(0) = theSelection.glue();
906         }
907         insert(p);
908         plainLeft();
909         push(p, true);
910 }
911
912
913 void MathCursor::GetPos(int & x, int & y)
914 {
915         x = xarray().xo() + xarray().pos2x(cursor().pos_);
916         y = xarray().yo();
917 }
918
919
920 MathTextCodes MathCursor::nextCode() const
921 {
922         return array().GetCode(cursor().pos_); 
923 }
924
925
926 MathTextCodes MathCursor::prevCode() const
927 {
928         return array().GetCode(cursor().pos_ - 1); 
929 }
930
931
932 MathInset * MathCursor::par() const
933 {
934         return cursor().par_;
935 }
936
937
938 InsetFormulaBase const * MathCursor::formula()
939 {
940         return formula_;
941 }
942
943
944 int MathCursor::pos() const
945 {
946         return cursor().pos_;
947 }
948
949
950 bool MathCursor::InMacroMode() const
951 {
952         return macro_mode;
953 }
954
955
956 bool MathCursor::Selection() const
957 {
958         return selection;
959 }
960
961
962 void MathCursor::clearLastCode()
963 {
964         lastcode = LM_TC_MIN;
965 }
966
967
968 void MathCursor::setLastCode(MathTextCodes t)
969 {
970         lastcode = t;
971 }
972
973
974 MathTextCodes MathCursor::getLastCode() const
975 {
976         return lastcode;
977 }
978
979
980 MathInset * MathCursor::enclosing(MathInsetTypes t, int & idx) const
981 {
982         for (int i = Cursor_.size() - 1; i >= 0; --i) {
983                 //lyxerr << "checking level " << i << "\n";
984                 if (Cursor_[i].par_->GetType() == t) {
985                         idx = Cursor_[i].idx_;
986                         return Cursor_[i].par_;
987                 }
988         }
989         return 0;
990 }
991
992
993 void MathCursor::pullArg(bool goright)
994 {
995         // pullArg
996         dump("pullarg");
997         MathArray a = array();
998         if (pop()) {
999                 array().erase(cursor().pos_);
1000                 array().insert(cursor().pos_, a);
1001                 if (goright) 
1002                         cursor().pos_ += a.size();
1003         }
1004 }
1005
1006
1007 MathStyles MathCursor::style() const
1008 {
1009         return xarray().style();
1010 }
1011
1012
1013 void MathCursor::normalize() const
1014 {
1015 #ifdef WITH_WARNINGS
1016 #warning This is evil!
1017 #endif
1018         MathCursor * it = const_cast<MathCursor *>(this);
1019
1020         if (cursor().idx_ < 0 || cursor().idx_ > cursor().par_->nargs())
1021                 lyxerr << "this should not really happen - 1\n";
1022         it->cursor().idx_    = max(cursor().idx_, 0);
1023         it->cursor().idx_    = min(cursor().idx_, cursor().par_->nargs());
1024
1025         if (cursor().pos_ < 0 || cursor().pos_ > array().size())
1026                 lyxerr << "this should not really happen - 2\n";
1027         it->cursor().pos_ = max(cursor().pos_, 0);
1028         it->cursor().pos_ = min(cursor().pos_, array().size());
1029 }
1030
1031
1032 int MathCursor::col() const
1033 {
1034         return par()->col(cursor().idx_);
1035 }
1036
1037
1038 int MathCursor::row() const
1039 {
1040         return par()->row(cursor().idx_);
1041 }
1042
1043
1044 /*
1045 char MathCursorPos::GetChar() const
1046 {
1047         return array().GetChar(cursor().pos_);
1048 }
1049
1050
1051 string MathCursorPos::readString()
1052 {
1053         string s;
1054         int code = nextCode();
1055         for ( ; OK() && nextCode() == code; Next()) 
1056                 s += GetChar();
1057
1058         return s;
1059 }
1060 */
1061
1062
1063 MathInset * MathCursor::prevInset() const
1064 {
1065         normalize();
1066         int c = cursor().pos_;
1067         if (!array().prev(c))
1068                 return 0;
1069         return array().nextInset(c);
1070 }
1071
1072
1073 MathInset * MathCursor::nextInset() const
1074 {
1075         normalize();
1076         return array().nextInset(cursor().pos_);
1077 }
1078
1079
1080 MathScriptInset * MathCursor::prevScriptInset() const
1081 {
1082         normalize();
1083         MathInset * p = array().prevInset(cursor().pos_);
1084         return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
1085 }
1086
1087
1088 MathSpaceInset * MathCursor::prevSpaceInset() const
1089 {
1090         normalize();
1091         MathInset * p = array().prevInset(cursor().pos_);
1092         return (p && p->isSpaceInset()) ? static_cast<MathSpaceInset *>(p) : 0;
1093 }
1094
1095
1096 MathArray & MathCursor::array() const
1097 {
1098         static MathArray dummy;
1099         if (!cursor().par_) {
1100                 lyxerr << "############  par_ not valid\n";
1101                 return dummy;
1102         }
1103
1104         if (cursor().idx_ < 0 || cursor().idx_ >= cursor().par_->nargs()) {
1105                 lyxerr << "############  idx_ " << cursor().idx_ << " not valid\n";
1106                 return dummy;
1107         }
1108
1109         return cursor().cell();
1110 }
1111
1112
1113 MathXArray & MathCursor::xarray() const
1114 {
1115         return cursor().xcell();
1116 }
1117
1118
1119 bool MathCursor::nextIsInset() const
1120 {
1121         return cursor().pos_ < array().size() && MathIsInset(nextCode());
1122 }
1123
1124
1125 bool MathCursor::prevIsInset() const
1126 {
1127         return cursor().pos_ > 0 && MathIsInset(prevCode());
1128 }
1129
1130
1131 int MathCursor::xpos() const 
1132 {
1133         normalize();
1134         return xarray().pos2x(cursor().pos_);
1135 }
1136
1137
1138 void MathCursor::gotoX(int x)
1139 {
1140         cursor().pos_ = xarray().x2pos(x);      
1141 }
1142
1143
1144 void MathCursor::idxNext()
1145 {
1146         cursor().par_->idxNext(cursor().idx_, cursor().pos_);
1147 }
1148
1149
1150 void MathCursor::idxPrev()
1151 {
1152         cursor().par_->idxPrev(cursor().idx_, cursor().pos_);
1153 }
1154
1155
1156 void MathCursor::splitCell()
1157 {
1158         if (cursor().idx_ == cursor().par_->nargs() - 1) 
1159                 return;
1160         MathArray ar = array();
1161         ar.erase(0, cursor().pos_);
1162         array().erase(cursor().pos_, array().size());
1163         ++cursor().idx_;
1164         cursor().pos_ = 0;
1165         array().insert(0, ar);
1166 }
1167
1168
1169 void MathCursor::breakLine()
1170 {
1171         MathMatrixInset * p = static_cast<MathMatrixInset *>(formula()->par());
1172         if (p->GetType() == LM_OT_SIMPLE || p->GetType() == LM_OT_EQUATION) {
1173                 p->mutate(LM_OT_EQNARRAY);
1174                 p->addRow(0);
1175                 cursor().idx_ = p->nrows();
1176                 cursor().pos_ = 0;
1177         } else {
1178                 p->addRow(row());
1179
1180                 // split line
1181                 const int r = row();
1182                 for (int c = col() + 1; c < p->ncols(); ++c) {
1183                         const int i1 = p->index(r, c);
1184                         const int i2 = p->index(r + 1, c);      
1185                         lyxerr << "swapping cells " << i1 << " and " << i2 << "\n";
1186                         p->cell(i1).swap(p->cell(i2));
1187                 }
1188
1189                 // split cell
1190                 splitCell();
1191                 p->cell(cursor().idx_).swap(p->cell(cursor().idx_ + p->ncols() - 1));
1192         }
1193 }
1194
1195
1196 char MathCursor::valign() const
1197 {
1198         int idx;
1199         MathGridInset * p =
1200                 static_cast<MathGridInset *>(enclosing(LM_OT_MATRIX, idx));
1201         return p ? p->valign() : 0;
1202 }
1203
1204
1205 char MathCursor::halign() const
1206 {
1207         int idx;
1208         MathGridInset * p =
1209                 static_cast<MathGridInset *>(enclosing(LM_OT_MATRIX, idx));
1210         return p ? p->halign(idx % p->ncols()) : 0;
1211 }
1212
1213
1214 MathCursorPos MathCursor::firstSelectionPos() const
1215 {
1216         MathCursorPos anc = normalAnchor();
1217         return anc < cursor() ? anc : cursor(); 
1218 }
1219
1220
1221 MathCursorPos MathCursor::lastSelectionPos() const
1222 {
1223         MathCursorPos anc = normalAnchor();
1224         return anc < cursor() ? cursor() : anc; 
1225 }
1226
1227
1228 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1229 {
1230         MathCursorPos anc = normalAnchor();
1231         if (anc < cursor()) {
1232                 i1 = anc;
1233                 i2 = cursor();
1234         } else {
1235                 i1 = cursor();
1236                 i2 = anc;
1237         }
1238 }
1239
1240
1241 MathCursorPos & MathCursor::cursor()
1242 {
1243         return Cursor_.back();
1244 }
1245
1246
1247 MathCursorPos const & MathCursor::cursor() const
1248 {
1249         return Cursor_.back();
1250 }
1251
1252
1253
1254 ////////////////////////////////////////////////////////////////////////
1255
1256
1257 bool operator==(MathCursorPos const & ti, MathCursorPos const & it)
1258 {
1259         return ti.par_ == it.par_ && ti.idx_ == it.idx_ && ti.pos_ == it.pos_;
1260 }
1261
1262
1263 bool operator<(MathCursorPos const & ti, MathCursorPos const & it)
1264 {
1265         if (ti.par_ != it.par_) {
1266                 lyxerr << "can't compare cursor and anchor in different insets\n";
1267                 return true;
1268         }
1269         if (ti.idx_ != it.idx_)
1270                 return ti.idx_ < it.idx_;
1271         return ti.pos_ < it.pos_;
1272 }
1273
1274
1275 MathArray & MathCursorPos::cell(int idx) const
1276 {
1277         return par_->cell(idx);
1278 }
1279
1280 MathArray & MathCursorPos::cell() const
1281 {
1282         return par_->cell(idx_);
1283 }
1284
1285
1286 MathXArray & MathCursorPos::xcell(int idx) const
1287 {
1288         return par_->xcell(idx);
1289 }
1290
1291
1292 MathXArray & MathCursorPos::xcell() const
1293 {
1294         return par_->xcell(idx_);
1295 }
1296
1297
1298 MathCursorPos MathCursor::normalAnchor() const
1299 {
1300         // use Anchor on the same level as Cursor
1301         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1302         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1303                 // anchor is behind cursor -> move anchor behind the inset
1304                 normal.cell().next(normal.pos_);
1305         }
1306         //lyxerr << "normalizing: from " << Anchor_[Anchor_.size() - 1] << " to "
1307         //      << normal << "\n";
1308         return normal;
1309 }
1310
1311
1312 bool MathCursorPos::idxUp()
1313 {
1314         return par_->idxUp(idx_, pos_);
1315 }
1316
1317
1318 bool MathCursorPos::idxDown()
1319 {
1320         return par_->idxDown(idx_, pos_);
1321 }
1322
1323
1324 bool MathCursorPos::idxLeft()
1325 {
1326         return par_->idxLeft(idx_, pos_);
1327 }
1328
1329
1330 bool MathCursorPos::idxRight()
1331 {
1332         return par_->idxRight(idx_, pos_);
1333 }