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