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