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