]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
keep empty super/subscript a bit longer
[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                         if (oldsel) 
750                                 SelPaste();
751                 }
752                 p->Metrics(p->size());
753         }
754 }
755
756
757 void MathCursor::MacroModeOpen()
758 {
759         if (!macro_mode) {
760                 imacro = new MathFuncInset("");
761                 insert(imacro);
762                 macro_mode = true;
763         } else
764                 lyxerr << "Math Warning: Already in macro mode" << endl;
765 }
766
767
768 void MathCursor::MacroModeClose()
769 {
770         if (macro_mode)  {
771                 macro_mode = false;
772                 latexkeys const * l = in_word_set(imacro->name());
773                 if (!imacro->name().empty()
774                                 && (!l || (l && IsMacro(l->token, l->id)))
775                                 && !MathMacroTable::hasTemplate(imacro->name()))
776                 {
777                         if (!l) {
778                                 //imacro->SetName(macrobf);
779                                 // This guarantees that the string will be removed by destructor
780                                 imacro->SetType(LM_OT_UNDEF);
781                         } else
782                                 imacro->SetName(l->name);
783                 } else {
784                         Left();
785                         array().erase(cursor().pos_);
786                         if (l || MathMacroTable::hasTemplate(imacro->name())) 
787                                 Interpret(imacro->name());
788                         imacro->SetName(string());
789                 }
790                 imacro = 0;
791         }
792 }
793
794
795 void MathCursor::SelCopy()
796 {
797         seldump("SelCopy");
798         if (selection) {
799                 theSelection.grab(*this);
800                 SelClear();
801         }
802 }
803
804
805 void MathCursor::SelCut()
806 {
807         seldump("SelCut");
808         if (selection) {
809                 theSelection.grab(*this);
810                 theSelection.erase(*this);
811                 SelClear();
812         }
813 }
814
815
816 void MathCursor::SelDel()
817 {
818         seldump("SelDel");
819         if (selection) {
820                 theSelection.erase(*this);
821                 SelClear();
822         }
823 }
824
825
826 void MathCursor::SelPaste()
827 {
828         seldump("SelPaste");
829         theSelection.paste(*this);
830         SelClear();
831 }
832
833
834 void MathCursor::SelHandle(bool sel)
835 {
836         if (sel && !selection)
837                 SelStart();
838         if (!sel && selection)
839                 SelClear();
840 }
841
842
843 void MathCursor::SelStart()
844 {
845         seldump("SelStart");
846         if (selection)
847                 return;
848
849         Anchor_ = Cursor_;
850         selection = true;
851 }
852
853
854 void MathCursor::SelClear()
855 {
856         selection = false;
857 }
858
859
860 void MathCursor::drawSelection(Painter & pain) const
861 {
862         if (!selection)
863                 return;
864
865         MathCursorPos i1;
866         MathCursorPos i2;
867         getSelection(i1, i2);
868
869         //lyxerr << "selection from: " << i1 << " to " << i2 << "\n";
870
871         if (i1.idx_ == i2.idx_) {
872                 MathXArray & c = i1.xcell();
873                 int x1 = c.xo() + c.pos2x(i1.pos_);
874                 int y1 = c.yo() - c.ascent();
875                 int x2 = c.xo() + c.pos2x(i2.pos_);
876                 int y2 = c.yo() + c.descent();
877                 pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
878         } else {
879
880                 std::vector<int> indices = i1.par_->idxBetween(i1.idx_, i2.idx_);
881                 for (unsigned i = 0; i < indices.size(); ++i) {
882                         MathXArray & c = i1.xcell(indices[i]);
883                         int x1 = c.xo();
884                         int y1 = c.yo() - c.ascent();
885                         int x2 = c.xo() + c.width();
886                         int y2 = c.yo() + c.descent();
887                         pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
888                 }
889         }
890 }
891
892
893 void MathCursor::handleFont(MathTextCodes t)
894 {
895         if (selection) {
896                 MathCursorPos i1;
897                 MathCursorPos i2;
898                 getSelection(i1, i2); 
899                 if (i1.idx_ == i2.idx_) {
900                         MathArray & ar = i1.cell();
901                         for (int pos = i1.pos_; pos != i2.pos_; ar.next(pos))
902                                 if (!ar.isInset(pos) && isalnum(ar.GetChar(pos))) { 
903                                         MathTextCodes c = ar.GetCode(pos) == t ? LM_TC_VAR : t;
904                                         ar.setCode(pos, c);
905                                 }
906                 }
907         } else {
908                 lastcode = (lastcode == t) ? LM_TC_VAR : t;
909         }
910 }
911
912
913 void MathCursor::handleAccent(string const & name, int code)
914 {
915         MathDecorationInset * p = new MathDecorationInset(name, code);
916         if (selection) {
917                 SelCut();
918                 p->cell(0) = theSelection.glue();
919         }
920         insert(p);
921         push(p, true);
922 }
923
924
925 void MathCursor::handleDelim(int l, int r)
926 {
927         MathDelimInset * p = new MathDelimInset(l, r);
928         if (selection) {
929                 SelCut();
930                 p->cell(0) = theSelection.glue();
931         }
932         insert(p);
933         plainLeft();
934         push(p, true);
935 }
936
937
938 void MathCursor::GetPos(int & x, int & y)
939 {
940         x = xarray().xo() + xarray().pos2x(cursor().pos_);
941         y = xarray().yo();
942 }
943
944
945 MathTextCodes MathCursor::nextCode() const
946 {
947         return array().GetCode(cursor().pos_); 
948 }
949
950
951 MathTextCodes MathCursor::prevCode() const
952 {
953         return array().GetCode(cursor().pos_ - 1); 
954 }
955
956
957 MathInset * MathCursor::par() const
958 {
959         return cursor().par_;
960 }
961
962
963 InsetFormulaBase const * MathCursor::formula()
964 {
965         return formula_;
966 }
967
968
969 int MathCursor::pos() const
970 {
971         return cursor().pos_;
972 }
973
974
975 bool MathCursor::InMacroMode() const
976 {
977         return macro_mode;
978 }
979
980
981 bool MathCursor::Selection() const
982 {
983         return selection;
984 }
985
986
987 void MathCursor::clearLastCode()
988 {
989         lastcode = LM_TC_MIN;
990 }
991
992
993 void MathCursor::setLastCode(MathTextCodes t)
994 {
995         lastcode = t;
996 }
997
998
999 MathTextCodes MathCursor::getLastCode() const
1000 {
1001         return lastcode;
1002 }
1003
1004
1005 MathInset * MathCursor::enclosing(MathInsetTypes t, int & idx) const
1006 {
1007         for (int i = Cursor_.size() - 1; i >= 0; --i) {
1008                 //lyxerr << "checking level " << i << "\n";
1009                 if (Cursor_[i].par_->GetType() == t) {
1010                         idx = Cursor_[i].idx_;
1011                         return Cursor_[i].par_;
1012                 }
1013         }
1014         return 0;
1015 }
1016
1017
1018 void MathCursor::pullArg(bool goright)
1019 {
1020         // pullArg
1021         dump("pullarg");
1022         MathArray a = array();
1023         if (pop()) {
1024                 array().erase(cursor().pos_);
1025                 array().insert(cursor().pos_, a);
1026                 if (goright) 
1027                         cursor().pos_ += a.size();
1028         }
1029 }
1030
1031
1032 MathStyles MathCursor::style() const
1033 {
1034         return xarray().style();
1035 }
1036
1037
1038 void MathCursor::normalize() const
1039 {
1040 #ifdef WITH_WARNINGS
1041 #warning This is evil!
1042 #endif
1043         MathCursor * it = const_cast<MathCursor *>(this);
1044
1045         if (cursor().idx_ < 0 || cursor().idx_ > cursor().par_->nargs())
1046                 lyxerr << "this should not really happen - 1\n";
1047         it->cursor().idx_    = max(cursor().idx_, 0);
1048         it->cursor().idx_    = min(cursor().idx_, cursor().par_->nargs());
1049
1050         if (cursor().pos_ < 0 || cursor().pos_ > array().size())
1051                 lyxerr << "this should not really happen - 2\n";
1052         it->cursor().pos_ = max(cursor().pos_, 0);
1053         it->cursor().pos_ = min(cursor().pos_, array().size());
1054 }
1055
1056
1057 int MathCursor::col() const
1058 {
1059         return par()->col(cursor().idx_);
1060 }
1061
1062
1063 int MathCursor::row() const
1064 {
1065         return par()->row(cursor().idx_);
1066 }
1067
1068
1069 /*
1070 char MathCursorPos::GetChar() const
1071 {
1072         return array().GetChar(cursor().pos_);
1073 }
1074
1075
1076 string MathCursorPos::readString()
1077 {
1078         string s;
1079         int code = nextCode();
1080         for ( ; OK() && nextCode() == code; Next()) 
1081                 s += GetChar();
1082
1083         return s;
1084 }
1085 */
1086
1087
1088 MathInset * MathCursor::prevInset() const
1089 {
1090         normalize();
1091         int c = cursor().pos_;
1092         if (!array().prev(c))
1093                 return 0;
1094         return array().nextInset(c);
1095 }
1096
1097
1098 MathInset * MathCursor::nextInset() const
1099 {
1100         normalize();
1101         return array().nextInset(cursor().pos_);
1102 }
1103
1104
1105 MathUpDownInset * MathCursor::nearbyUpDownInset() const
1106 {
1107         normalize();
1108         MathInset * p = array().prevInset(cursor().pos_);
1109         if (p && p->isUpDownInset())
1110                 return static_cast<MathUpDownInset *>(p);
1111         p = array().nextInset(cursor().pos_);
1112         if (p && p->isUpDownInset())
1113                 return static_cast<MathUpDownInset *>(p);
1114         return 0;
1115 }
1116
1117
1118 MathArray & MathCursor::array() const
1119 {
1120         static MathArray dummy;
1121         if (!cursor().par_) {
1122                 lyxerr << "############  par_ not valid\n";
1123                 return dummy;
1124         }
1125
1126         if (cursor().idx_ < 0 || cursor().idx_ >= cursor().par_->nargs()) {
1127                 lyxerr << "############  idx_ " << cursor().idx_ << " not valid\n";
1128                 return dummy;
1129         }
1130
1131         return cursor().cell();
1132 }
1133
1134
1135 MathXArray & MathCursor::xarray() const
1136 {
1137         return cursor().xcell();
1138 }
1139
1140
1141 bool MathCursor::nextIsInset() const
1142 {
1143         return cursor().pos_ < array().size() && MathIsInset(nextCode());
1144 }
1145
1146
1147 bool MathCursor::prevIsInset() const
1148 {
1149         return cursor().pos_ > 0 && MathIsInset(prevCode());
1150 }
1151
1152
1153 int MathCursor::xpos() const 
1154 {
1155         normalize();
1156         return xarray().pos2x(cursor().pos_);
1157 }
1158
1159
1160 void MathCursor::gotoX(int x)
1161 {
1162         cursor().pos_ = xarray().x2pos(x);      
1163 }
1164
1165
1166 void MathCursor::idxNext()
1167 {
1168         cursor().par_->idxNext(cursor().idx_, cursor().pos_);
1169 }
1170
1171
1172 void MathCursor::idxPrev()
1173 {
1174         cursor().par_->idxPrev(cursor().idx_, cursor().pos_);
1175 }
1176
1177
1178 void MathCursor::splitCell()
1179 {
1180         if (cursor().idx_ == cursor().par_->nargs() - 1) 
1181                 return;
1182         MathArray ar = array();
1183         ar.erase(0, cursor().pos_);
1184         array().erase(cursor().pos_, array().size());
1185         ++cursor().idx_;
1186         cursor().pos_ = 0;
1187         array().insert(0, ar);
1188 }
1189
1190
1191 void MathCursor::breakLine()
1192 {
1193         MathMatrixInset * p = static_cast<MathMatrixInset *>(formula()->par());
1194         if (p->GetType() == LM_OT_SIMPLE || p->GetType() == LM_OT_EQUATION) {
1195                 p->mutate(LM_OT_EQNARRAY);
1196                 p->addRow(0);
1197                 cursor().idx_ = p->nrows();
1198                 cursor().pos_ = 0;
1199         } else {
1200                 p->addRow(row());
1201
1202                 // split line
1203                 const int r = row();
1204                 for (int c = col() + 1; c < p->ncols(); ++c) {
1205                         const int i1 = p->index(r, c);
1206                         const int i2 = p->index(r + 1, c);      
1207                         lyxerr << "swapping cells " << i1 << " and " << i2 << "\n";
1208                         p->cell(i1).swap(p->cell(i2));
1209                 }
1210
1211                 // split cell
1212                 splitCell();
1213                 p->cell(cursor().idx_).swap(p->cell(cursor().idx_ + p->ncols() - 1));
1214         }
1215 }
1216
1217
1218 char MathCursor::valign() const
1219 {
1220         int idx;
1221         MathGridInset * p =
1222                 static_cast<MathGridInset *>(enclosing(LM_OT_MATRIX, idx));
1223         return p ? p->valign() : 0;
1224 }
1225
1226
1227 char MathCursor::halign() const
1228 {
1229         int idx;
1230         MathGridInset * p =
1231                 static_cast<MathGridInset *>(enclosing(LM_OT_MATRIX, idx));
1232         return p ? p->halign(idx % p->ncols()) : 0;
1233 }
1234
1235
1236 MathCursorPos MathCursor::firstSelectionPos() const
1237 {
1238         MathCursorPos anc = normalAnchor();
1239         return anc < cursor() ? anc : cursor(); 
1240 }
1241
1242
1243 MathCursorPos MathCursor::lastSelectionPos() const
1244 {
1245         MathCursorPos anc = normalAnchor();
1246         return anc < cursor() ? cursor() : anc; 
1247 }
1248
1249
1250 void MathCursor::getSelection(MathCursorPos & i1, MathCursorPos & i2) const
1251 {
1252         MathCursorPos anc = normalAnchor();
1253         if (anc < cursor()) {
1254                 i1 = anc;
1255                 i2 = cursor();
1256         } else {
1257                 i1 = cursor();
1258                 i2 = anc;
1259         }
1260 }
1261
1262
1263 MathCursorPos & MathCursor::cursor()
1264 {
1265         return Cursor_.back();
1266 }
1267
1268
1269 MathCursorPos const & MathCursor::cursor() const
1270 {
1271         return Cursor_.back();
1272 }
1273
1274
1275
1276 ////////////////////////////////////////////////////////////////////////
1277
1278
1279 bool operator==(MathCursorPos const & ti, MathCursorPos const & it)
1280 {
1281         return ti.par_ == it.par_ && ti.idx_ == it.idx_ && ti.pos_ == it.pos_;
1282 }
1283
1284
1285 bool operator<(MathCursorPos const & ti, MathCursorPos const & it)
1286 {
1287         if (ti.par_ != it.par_) {
1288                 lyxerr << "can't compare cursor and anchor in different insets\n";
1289                 return true;
1290         }
1291         if (ti.idx_ != it.idx_)
1292                 return ti.idx_ < it.idx_;
1293         return ti.pos_ < it.pos_;
1294 }
1295
1296
1297 MathArray & MathCursorPos::cell(int idx) const
1298 {
1299         return par_->cell(idx);
1300 }
1301
1302 MathArray & MathCursorPos::cell() const
1303 {
1304         return par_->cell(idx_);
1305 }
1306
1307
1308 MathXArray & MathCursorPos::xcell(int idx) const
1309 {
1310         return par_->xcell(idx);
1311 }
1312
1313
1314 MathXArray & MathCursorPos::xcell() const
1315 {
1316         return par_->xcell(idx_);
1317 }
1318
1319
1320 MathCursorPos MathCursor::normalAnchor() const
1321 {
1322         // use Anchor on the same level as Cursor
1323         MathCursorPos normal = Anchor_[Cursor_.size() - 1];
1324         if (Cursor_.size() < Anchor_.size() && !(normal < cursor())) {
1325                 // anchor is behind cursor -> move anchor behind the inset
1326                 normal.cell().next(normal.pos_);
1327         }
1328         //lyxerr << "normalizing: from " << Anchor_[Anchor_.size() - 1] << " to "
1329         //      << normal << "\n";
1330         return normal;
1331 }
1332
1333
1334 bool MathCursorPos::idxUp()
1335 {
1336         return par_->idxUp(idx_, pos_);
1337 }
1338
1339
1340 bool MathCursorPos::idxDown()
1341 {
1342         return par_->idxDown(idx_, pos_);
1343 }
1344
1345
1346 bool MathCursorPos::idxLeft()
1347 {
1348         return par_->idxLeft(idx_, pos_);
1349 }
1350
1351
1352 bool MathCursorPos::idxRight()
1353 {
1354         return par_->idxRight(idx_, pos_);
1355 }