]> git.lyx.org Git - lyx.git/blob - src/mathed/math_cursor.C
Add support for multline and alignat environments from amsmath.
[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, Mathed & 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 FORMS_H_LOCATION
24 #include "math_inset.h"
25 #include "math_parser.h"
26 #include "math_cursor.h"
27 #include "math_macro.h"
28 #include "math_root.h"
29 #include "support/lstrings.h"
30 #include "debug.h"
31 #include "LColor.h"
32 #include "Painter.h"
33
34 static LyxArrayBase * selarray = 0;
35
36 using std::endl;
37
38 // This was very smaller, I'll change it later 
39 static inline
40 bool IsMacro(short tok, int id)
41 {
42    return (tok != LM_TK_STACK && tok != LM_TK_FRAC && tok != LM_TK_SQRT
43            && tok != LM_TK_WIDE
44            && tok != LM_TK_SPACE && tok != LM_TK_DOTS
45            && tok != LM_TK_FUNCLIM
46            && tok != LM_TK_BIGSYM && tok != LM_TK_ACCENT && 
47            !(tok == LM_TK_SYM && id < 255));
48 }
49
50 static int const MAX_STACK_ITEMS = 32;
51
52 struct MathStackXIter {
53     int i, imax;
54     MathedXIter * item;
55     
56     MathStackXIter(int n = MAX_STACK_ITEMS): imax(n) {
57         item = new MathedXIter[imax];
58         i = 0;
59     }
60     
61     MathStackXIter(MathStackXIter & stk);
62     
63     ~MathStackXIter() {
64         delete[] item;
65     }
66    
67     void push(MathedXIter ** a) {
68         *a = &item[i++];
69     }
70       
71     MathedXIter * pop() {
72         --i;
73         return &item[i - 1];
74     }
75       
76     MathedXIter * Item(int idx) {
77        return (idx + 1 <= i) ? &item[i - idx - 1] : 0;
78     }
79
80     void Reset() {
81         i = 0;
82     }
83    
84     bool Full() {
85         return i >= MAX_STACK_ITEMS;
86     }
87    
88     bool Empty() {
89         return i <= 1;
90     }
91
92     int Level() { return i; } 
93     
94 } mathstk, *selstk = 0;
95
96
97 MathStackXIter::MathStackXIter(MathStackXIter & stk)
98 {
99     imax = stk.imax;
100     item = new MathedXIter[imax];
101     i = stk.i;
102     for (int k = 0; k < i; ++k) {
103         item[k].SetData(stk.item[k].getPar());
104         item[k].GoBegin();
105         item[k].goPosAbs(stk.item[k].getPos());
106     }
107 }
108
109
110 /***----------------  Mathed Cursor  ---------------------------***/
111   
112 MathedCursor::MathedCursor(MathParInset * p) // : par(p)
113 {
114     accent = 0;
115     anchor = 0;
116     lastcode = LM_TC_MIN;
117     SetPar(p);
118 //    selarray = 0;     
119     if (!MathMacroTable::built)
120         MathMacroTable::mathMTable.builtinMacros();
121 }
122
123
124 void MathedCursor::SetPar(MathParInset * p)
125 {
126    win = 0;
127    is_visible = False;
128    macro_mode = false;
129    selection = false; // not SelClear() ?
130    mathstk.Reset();
131    mathstk.push(&cursor);
132    par = p;
133    cursor->SetData(par);
134 }
135
136
137 void MathedCursor::draw(Painter & pain, int x, int y)
138 {
139         //    lyxerr << "Cursor[" << x << " " << y << "] ";
140         //win = pm;    // win = (mathedCanvas) ? mathedCanvas: pm;
141         par->Metrics();
142         int w = par->Width() + 2;
143         int a = par->Ascent() + 1;
144         int h = par->Height() + 1;
145         if (par->GetType() > LM_OT_PAR) { a += 4;  h += 8; }
146         
147         pain.rectangle(x - 1, y - a, w, h, LColor::mathframe);
148         
149         par->draw(pain, x, y);
150         cursor->Adjust();
151 }
152
153
154 void MathedCursor::Redraw(Painter & pain)
155 {  
156         lyxerr[Debug::MATHED] << "Mathed: Redrawing!" << endl;
157         par->Metrics();
158         int w = par->Width(), h = par->Height();
159         int x;
160         int y;
161         par->GetXY(x, y);
162         //mathed_set_font(LM_TC_VAR, 1);
163         pain.fillRectangle(x, y - par->Ascent(),
164                            x + w, y - par->Ascent() + h,
165                            LColor::mathbg);
166         par->draw(pain, x, y);
167 }
168
169
170 bool MathedCursor::Left(bool sel)
171 {
172    if (macro_mode) {
173       MacroModeBack();
174       return true;
175    }
176     clearLastCode();
177    if (sel && !selection) SelStart();
178    if (!sel && selection) SelClear();
179    bool result = cursor->Prev();
180    if (!result && !mathstk.Empty()) {
181       cursor = mathstk.pop();
182       cursor->Adjust();
183       result = true;
184       if (selection) SelClear();
185    } else  
186      if (result && cursor->IsActive()) {
187         if (cursor->IsScript()) {
188            cursor->Prev();
189            if (!cursor->IsScript())
190              cursor->Next();
191            cursor->Adjust(); 
192            return true;
193         }
194         if (!selection) {
195             MathParInset * p = cursor->GetActiveInset();
196             if (!p)
197               return result;
198                 
199             p->setArgumentIdx(p->getMaxArgumentIdx());
200             mathstk.push(&cursor);
201             cursor->SetData(p);
202             cursor->GoLast();
203         }
204      } 
205    return result;  
206 }
207
208
209 // Leave the inset
210 bool MathedCursor::Pop()
211 {
212    if (!mathstk.Empty()) {
213       cursor = mathstk.pop();
214       cursor->Next(); 
215       return true;
216    }
217    return false;
218 }
219
220
221 // Go to the inset 
222 bool MathedCursor::Push()
223
224    if (cursor->IsActive()) {
225       MathParInset * p = cursor->GetActiveInset();
226        if (!p) return false;
227       mathstk.push(&cursor);
228       cursor->SetData(p);
229       return true;
230    }
231    return false;
232 }  
233
234
235 bool MathedCursor::Right(bool sel)
236 {  
237    if (macro_mode) {
238       MacroModeClose();
239       return true;
240    } 
241     clearLastCode();
242    if (sel && !selection) SelStart();
243    if (!sel && selection) SelClear();
244    bool result = false;
245  
246    if (cursor->IsActive()) {
247       if (cursor->IsScript()) {
248          cursor->Next();
249          // A script may be followed by another script
250          if (cursor->IsScript()) 
251            cursor->Next();
252          return true;
253       }
254       if (!selection) { 
255           MathParInset *p = cursor->GetActiveInset();
256           if (!p) {
257                   lyxerr << "Math error: Inset expected." << endl;
258               return cursor->Next();
259           }
260           p->setArgumentIdx(0);
261           mathstk.push(&cursor);
262           cursor->SetData(p);
263           result = true;
264       } else
265          result = cursor->Next();
266    } else {
267        if (cursor->GetChar()!= LM_TC_CR)
268          result = cursor->Next();
269      if (!result && !mathstk.Empty()) {
270         cursor = mathstk.pop();
271         cursor->Next();
272          cursor->Adjust();
273         result = true;
274         if (selection) SelClear();
275      }
276    }
277    return result;
278 }
279
280
281 void MathedCursor::SetPos(int x, int y)
282 {
283     int xp = 0;
284     
285     if (macro_mode) MacroModeClose();
286     lastcode = LM_TC_MIN;
287     mathstk.Reset();
288     mathstk.push(&cursor);
289     cursor->SetData(par);
290     cursor->fitCoord(x, y);
291     while (cursor->GetX()<x && cursor->OK()) {
292         if (cursor->IsActive()) {
293             MathParInset * p = cursor->GetActiveInset();
294             if (p->Inside(x, y)) {
295                 p->SetFocus(x, y);
296                 mathstk.push(&cursor);
297                 cursor->SetData(p);
298                 cursor->fitCoord(x, y);
299                 continue;
300             }
301         }
302         xp = cursor->GetX();
303         cursor->ipush();
304         if (!cursor->Next() && !Pop()) 
305           break;
306     }
307     if (x-xp < cursor->GetX()-x) cursor->ipop();
308     cursor->Adjust();
309 }
310    
311
312 void MathedCursor::Home()
313 {
314    if (macro_mode) MacroModeClose();
315     clearLastCode();
316    mathstk.Reset();
317    mathstk.push(&cursor);
318    cursor->GoBegin();
319 }
320
321
322 void MathedCursor::End()
323 {
324    if (macro_mode) MacroModeClose();
325     clearLastCode();
326    mathstk.Reset();
327    mathstk.push(&cursor);
328    cursor->GoLast();
329 }
330
331
332 MathMatrixInset * create_multiline(short int type, int cols)
333 {
334         int columns;
335         string align;
336         if (cols < 1)
337                 cols = 1;
338
339         switch (type) {
340         case LM_OT_ALIGNAT:
341         case LM_OT_ALIGNATN:
342                 columns = 2*cols;
343                 for (int i = 0; i < cols; ++i)
344                         align += "rl";
345                 break;
346         case LM_OT_MULTLINE:
347         case LM_OT_MULTLINEN:
348                 columns = 1;
349                 align = "c"; // This is incorrect!
350                 break;
351         case LM_OT_MPAR:
352         case LM_OT_MPARN:
353         default:
354                 columns = 3;
355                 align = "rcl";
356                 break;
357         }
358
359         MathMatrixInset * mt = new MathMatrixInset(columns, -1);
360         mt->SetAlign(' ', align);
361         return mt;
362 }
363
364 void MathedCursor::Insert(byte c, MathedTextCodes t)
365 {  
366    if (selection) SelDel();
367    
368    if (t == LM_TC_MIN)
369       t = lastcode;
370     
371    if (macro_mode && !(MathIsAlphaFont(t) || t == LM_TC_MIN))
372       MacroModeClose();
373         
374    if (t == LM_TC_CR) {
375       MathParInset * p = cursor->p;
376       if (p == par && p->GetType()<LM_OT_MPAR && p->GetType()>LM_OT_MIN) {
377          short int type = LM_OT_MPAR;
378          int cols = 1;
379          if (c >= '1' && c <= '9') {
380                  type = LM_OT_ALIGNAT;
381                  cols = c - '0';
382          } else if (c == 'm')
383                  type = LM_OT_MULTLINE;
384          else if (c == 'e')
385                  type = LM_OT_MPAR;
386
387          if (p->GetType() == LM_OT_PARN)
388              ++type;
389          MathMatrixInset * mt = create_multiline(type, cols);
390          mt->SetStyle(LM_ST_DISPLAY);
391          mt->SetType(type);
392          mt->SetData(p->GetData());
393          p->SetData(0);//BUG duda
394          delete p;
395          par = mt;
396          p = mt;
397          p->Metrics();
398          int pos = cursor->getPos();
399          cursor->SetData(par);
400          cursor->goPosAbs(pos);
401       }      
402       if (p &&  p->Permit(LMPF_ALLOW_CR)) {
403           cursor->addRow();
404       }
405    } else
406    if (t == LM_TC_TAB) {
407       MathParInset * p = cursor->p;
408       if (p &&  p->Permit(LMPF_ALLOW_TAB)) {
409           if (c) {
410               cursor->Insert(c, t);
411               cursor->checkTabs();
412           } else
413             cursor->goNextColumn();
414       } else // Navigate between arguments
415          if (p && p->GetType() == LM_OT_MACRO) {
416              if (p->getArgumentIdx() < p->getMaxArgumentIdx()) {
417                  p->setArgumentIdx(p->getArgumentIdx() + 1);
418                  cursor->SetData(p);
419                  return;
420              }
421          }       
422    } else {
423        if (macro_mode) {
424            if (MathIsAlphaFont(t) || t == LM_TC_MIN) {
425                MacroModeInsert(c);
426                return;
427            }
428        } 
429        if (accent) {
430                doAccent(c, t);
431        } else 
432          cursor->Insert(c, t);
433        lastcode = t;
434        
435        return;
436    }
437     clearLastCode();
438 }
439
440
441 void MathedCursor::Insert(MathedInset * p, int t)
442 {
443    if (macro_mode) MacroModeClose();
444    if (selection) {
445       if (MathIsActive(t)) {
446          SelCut();
447          static_cast<MathParInset*>(p)->SetData(selarray);
448       } else
449         SelDel();
450    }
451          
452    if (mathstk.i < MAX_STACK_ITEMS - 1) {
453        
454        if (accent && !MathIsActive(t)) {               
455                doAccent(p);
456        } else {
457            cursor->Insert(p, t);
458        
459            if (MathIsActive(t)) {
460                cursor->Prev();
461                Push();
462            }
463        }
464      
465    } else
466            lyxerr << "Math error: Full stack." << endl;
467 }
468
469
470 void MathedCursor::Delete() 
471 {   
472    if (macro_mode) return;
473    if (selection) {
474       SelDel();
475       return;
476    }
477    if (cursor->Empty() && !mathstk.Empty()) {
478       cursor = mathstk.pop();
479    } 
480 //   if (cursor->GetChar()!= LM_TC_TAB)
481     cursor->Delete();
482     cursor->checkTabs();
483 }
484
485
486 void MathedCursor::DelLine()
487 {  
488     if (macro_mode) MacroModeClose();
489     if (selection) {
490         SelDel();
491         return;
492     }
493     MathParInset *p= cursor->p;
494     if (p && p->GetType() <= LM_OT_MATRIX && p->GetType() >= LM_OT_MPAR) {
495         cursor->delRow();
496     }
497 }
498
499
500 bool MathedCursor::Up(bool sel)
501 {
502     bool result = false;
503    
504     if (macro_mode) MacroModeClose();
505     
506     if (sel && !selection) SelStart();
507     if (!sel && selection) SelClear();
508     
509
510     if (cursor->IsScript()) {
511         char cd = cursor->GetChar();
512         if (MathIsUp(cd)) {
513             Push();
514             return true;
515         } else {
516             // A subscript may be followed by a superscript
517             cursor->ipush();
518             cursor->Next();
519             if (MathIsUp(cursor->GetChar())) {
520                 Push();
521                 return true;
522             } else  // return to the previous state
523               cursor->ipop();
524       }
525    }    
526      
527     result = cursor->Up();
528     if (!result && cursor->p) {
529             MathParInset * p = cursor->p;   
530    
531         if (p->GetType() == LM_OT_SCRIPT) {
532             MathedXIter * cx = mathstk.Item(1);
533             bool is_down = (cx->GetChar() == LM_TC_DOWN);
534             cursor = mathstk.pop();
535             cursor->Next();
536             result =  (is_down) ? true: Up();
537         } else {
538             result = (p->getArgumentIdx() > 0);
539             if (result) {
540                 p->setArgumentIdx(p->getArgumentIdx() - 1);
541                 cursor->SetData(p);
542             }
543         }
544         if (!result && !mathstk.Empty()) {
545             cursor = mathstk.pop();
546             return Up();
547         }     
548     }
549     return result;
550 }
551
552
553 bool MathedCursor::Down(bool sel)
554 {
555     bool result = false;
556    
557     if (macro_mode) MacroModeClose();
558     
559     if (sel && !selection) SelStart();
560     if (!sel && selection) SelClear();
561 //    if (selection) SelClear();
562
563     if (cursor->IsScript()) {
564         char cd = cursor->GetChar(); 
565         if (MathIsDown(cd)) {
566             Push();
567             return true;
568         } else {
569             // A superscript may be followed by a subscript
570             cursor->ipush();
571             cursor->Next();
572             if (MathIsDown(cursor->GetChar())) {
573                 Push();
574                 return true;
575             } else
576               cursor->ipop();
577       }
578    }
579      
580     result = cursor->Down();
581     if (!result && cursor->p) {
582         MathParInset * p= cursor->p;   
583         if (p->GetType() == LM_OT_SCRIPT) {
584             MathedXIter * cx = mathstk.Item(1);
585             bool is_up = (cx->GetChar() == LM_TC_UP);
586             cursor = mathstk.pop();
587             cursor->Next();
588             result = (is_up) ? true: Down();
589         } else {
590             result = (p->getArgumentIdx() < p->getMaxArgumentIdx());
591             if (result) {
592                 p->setArgumentIdx(p->getArgumentIdx() + 1);
593                 cursor->SetData(p);
594             }
595         }
596         if (!result && !mathstk.Empty()) {
597             cursor = mathstk.pop();
598             return Down(sel);
599         }    
600     }
601     return result;
602 }
603
604
605 bool MathedCursor::Limits()
606 {
607    if (cursor->IsInset()) {
608       MathedInset * p = cursor->GetInset();
609       bool ol = p->GetLimits();
610       p->SetLimits(!ol);
611       return (ol!= p->GetLimits());
612    }
613    return false;
614 }
615
616
617 void MathedCursor::SetSize(short size)
618 {
619     MathParInset * p = cursor->p;
620     p->UserSetSize(size);
621     cursor->SetData(p);
622 }
623
624
625 void MathedCursor::setLabel(string const & label)
626 {  // ugly hack and possible bug
627     if (!cursor->setLabel(label))
628             lyxerr << "MathErr: Bad place to set labels." << endl;
629 }
630
631
632 void MathedCursor::setNumbered()
633 {  // another ugly hack
634     MathedRowSt * crow = cursor->crow;
635     if (!crow) return;    
636     crow->setNumbered(!crow->isNumbered());
637 }
638
639
640 void MathedCursor::Interpret(string const & s)
641 {
642     MathedInset * p = 0;
643     latexkeys * l = 0;
644     MathedTextCodes tcode = LM_TC_INSET;
645     
646     if (s[0] == '^' || s[0] == '_') {
647         char c = cursor->GetChar();
648         if (MathIsUp(c) && s[0] == '^' || MathIsDown(c) && s[0] == '_') {
649             Push();
650             return;
651         } else // A script may be followed by a script
652           if (MathIsUp(c)  || MathIsDown(c)) { 
653             cursor->ipush();
654             cursor->Next();
655             c = cursor->GetChar();
656             if (MathIsUp(c) && s[0] == '^' || MathIsDown(c) && s[0] == '_') {
657                 Push();
658                 return;
659             } else
660               cursor->ipop();
661         }
662         p = new MathParInset(LM_ST_SCRIPT, "", LM_OT_SCRIPT);
663         Insert (p, (s[0] == '_') ? LM_TC_DOWN: LM_TC_UP); 
664         return;
665     } else   
666       if (s[0] == '!' || s[0] == ','  || s[0] == ':' || s[0] == ';') {
667           int sp = ((s[0] == ',') ? 1:((s[0] == ':') ? 2:((s[0] == ';') ? 3: 0))); 
668           p = new MathSpaceInset(sp);
669           Insert(p);
670           return;
671       } else  
672       l = in_word_set(s);
673     
674     if (!l) {       
675         p = MathMacroTable::mathMTable.getMacro(s);
676         if (!p) {
677             lyxerr[Debug::MATHED] << "Macro2 " << s << ' ' << tcode << endl;
678             if (s == "root") {
679                 p = new MathRootInset();
680                 tcode = LM_TC_ACTIVE_INSET;
681             } else
682               p = new MathFuncInset(s, LM_OT_UNDEF);
683         } else {
684             tcode = static_cast<MathMacro*>(p)->getTCode();
685             lyxerr[Debug::MATHED] << "Macro2 " << s << ' ' << tcode << endl;
686         }
687     } else {
688         MathedInsetTypes fractype = LM_OT_FRAC;
689         switch (l->token) {
690          case LM_TK_BIGSYM:
691          {
692              p = new MathBigopInset(l->name, l->id);
693              break;
694          }
695          case LM_TK_SYM:
696          {                   
697              if (l->id<255) {
698                  Insert(static_cast<byte>(l->id), MathIsBOPS(l->id) ? 
699                         LM_TC_BOPS: LM_TC_SYMB);            
700              } else {
701                  p = new MathFuncInset(l->name);
702              }
703              break;
704          }  
705          case LM_TK_STACK:
706             fractype = LM_OT_STACKREL;
707             lyxerr[Debug::MATHED] << " i:stackrel " << endl;
708          case LM_TK_FRAC: 
709          {       
710              p = new MathFracInset(fractype);
711              tcode = LM_TC_ACTIVE_INSET;
712              break;
713          }
714          case LM_TK_SQRT: 
715          {       
716              p = new MathSqrtInset; 
717              tcode = LM_TC_ACTIVE_INSET;
718              break;
719          }
720          case LM_TK_WIDE: 
721          {       
722              p = new MathDecorationInset(l->id); 
723              tcode = LM_TC_ACTIVE_INSET;
724              break;
725          } 
726          case  LM_TK_FUNCLIM:
727          {
728              p = new MathFuncInset(l->name, LM_OT_FUNCLIM);
729              break;
730          }
731          case LM_TK_SPACE:
732          {
733              p = new MathSpaceInset(l->id);
734              break;
735          }         
736          case LM_TK_DOTS: 
737          {
738              p = new MathDotsInset(l->name, l->id);
739              break;
740          }         
741          case LM_TK_ACCENT:
742             setAccent(l->id);
743             break;
744          case LM_TK_MACRO:
745             p = MathMacroTable::mathMTable.getMacro(s);
746             tcode = static_cast<MathMacro*>(p)->getTCode();
747             lyxerr[Debug::MATHED] << "Macro " << s << ' ' << tcode << endl;
748             break;
749          default:
750          {
751              p = new MathFuncInset(l->name);
752              break;
753          }
754         }
755     }
756     if (p) {
757         Insert(p, tcode);
758         par->Metrics();
759     }
760 }
761
762
763 bool MathedCursor::pullArg()
764
765     if (cursor->IsActive()) {
766         MathParInset * p = cursor->GetActiveInset();
767         if (!p) { 
768             return false;
769         }
770         LyxArrayBase * a = p->GetData();
771         p->SetData(0);
772         Delete();
773         if (a) {
774             cursor->Merge(a);
775             cursor->Adjust();
776         }
777         
778         return true;
779     }
780     return false;
781 }  
782  
783
784 void MathedCursor::MacroModeOpen()
785 {
786    if (!macro_mode)  {
787       imacro = new MathFuncInset("");
788       Insert (imacro);
789       macro_mode = true;
790    } else
791            lyxerr << "Mathed Warning: Already in macro mode" << endl;
792 }
793
794
795 void MathedCursor::MacroModeClose()
796 {
797    if (macro_mode)  {
798       macro_mode = false;
799       latexkeys * l = in_word_set(imacro->GetName());
800       if (!imacro->GetName().empty()
801           && (!l || (l && IsMacro(l->token, l->id))) && 
802           !MathMacroTable::mathMTable.getMacro(imacro->GetName())) {
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          if (cursor->GetInset()->GetType() == LM_OT_ACCENT) {
812              setAccent(static_cast<MathAccentInset*>(cursor->GetInset())->getAccentCode());
813          }
814          cursor->Delete();
815          if (l || MathMacroTable::mathMTable.getMacro(imacro->GetName())) {
816             Interpret(imacro->GetName());
817          }
818          imacro->SetName("");
819       }
820       imacro = 0;
821    }  
822 }
823
824
825 void MathedCursor::MacroModeBack()
826 {
827    if (macro_mode) {
828      if (!imacro->GetName().empty()) {
829         imacro->SetName(imacro->GetName().substr(0, imacro->GetName().length() - 1));
830         imacro->Metrics();
831      } else 
832         MacroModeClose();
833    } else
834            lyxerr << "Mathed Warning: we are not in macro mode" << endl;
835 }
836
837
838 void MathedCursor::MacroModeInsert(char c)
839 {
840    if (macro_mode) {
841       imacro->SetName(imacro->GetName() + c);
842       imacro->Metrics();
843    } else
844            lyxerr << "Mathed Warning: we are not in macro mode" << endl;
845 }
846
847
848 void MathedCursor::SelCopy()
849 {
850     if (selection) {
851         int p1 = (cursor->pos < selpos) ? cursor->pos: selpos;
852         int p2 = (cursor->pos > selpos) ? cursor->pos: selpos;
853         selarray = cursor->Copy(p1, p2);
854         cursor->Adjust();
855         SelClear();
856     }
857 }
858
859
860 void MathedCursor::SelCut()
861 {   
862     if (selection) {
863         if (cursor->pos == selpos) return;
864         
865         int p1 = (cursor->pos < selpos) ? cursor->pos: selpos;
866         int p2 = (cursor->pos > selpos) ? cursor->pos: selpos;
867         selarray = cursor->Copy(p1, p2);
868         cursor->Clean(selpos);
869         cursor->Adjust();
870         SelClear();
871     }
872 }
873
874
875 void MathedCursor::SelDel()
876 {
877 //    lyxerr << "Deleting sel "
878     if (selection) {    
879         if (cursor->pos == selpos) return;
880         cursor->Clean(selpos);
881         cursor->Adjust();
882         SelClear();
883     }
884 }
885
886
887 void MathedCursor::SelPaste()
888 {
889 //    lyxerr << "paste " << selarray << " " << curor->pos;
890     if (selection) SelDel();
891     if (selarray) {
892         cursor->Merge(selarray);
893         cursor->Adjust();
894     }
895 }
896
897
898 void MathedCursor::SelStart()
899 {
900         lyxerr[Debug::MATHED] << "Starting sel " << endl;
901     if (!anchor) {
902         selpos = cursor->pos;   
903         selstk = new MathStackXIter(mathstk); 
904         anchor = selstk->Item(-1); 
905         anchor->SetData(cursor->p);
906         anchor->GoBegin();
907         anchor->goPosAbs(selpos);
908         selection = true;
909         
910     }
911 }
912
913
914 void MathedCursor::SelClear()
915 {   
916         lyxerr[Debug::MATHED] << "Clearing sel " << endl;
917     selection = false;
918     delete selstk;
919     selstk = 0;
920     anchor = 0;
921 }
922
923
924
925 // Anchor position must be at the same level that stack.
926 void MathedCursor::SelBalance()
927 {
928     int d = mathstk.Level() - selstk->Level();
929
930     // If unbalanced, balance them
931     while (d != 0) {
932         if (d < 0) {
933 //            lyxerr << "b[" << mathstk.Level() << " " << selstk->Level << " " << anchor->GetX() << " " << cursor->GetX() << "]";
934             anchor = selstk->pop();
935             if (anchor->GetX() >= cursor->GetX()) 
936               anchor->Next();
937         } else {
938 //            lyxerr <<"a[" << mathstk.Level() << " " << selstk->Level() <<"]";
939             Pop();
940         }
941         d = mathstk.Level() - selstk->Level();
942     }
943
944     // Once balanced the levels, check that they are at the same paragraph
945     selpos = anchor->pos;
946
947
948
949 void MathedCursor::SelGetArea(int ** xp, int ** yp, int & np)
950 {   
951     static int xpoint[10];
952     static int ypoint[10];
953
954     if (!selection) {
955         np = 0;
956         xpoint[0] = 0;
957         ypoint[0] = 0;
958         *xp = &xpoint[0];
959         *yp = &ypoint[0];
960         return;
961     }
962     
963     // single row selection
964     int i = 0;
965     int a;
966     int d;
967     int a1;
968     int d1;
969
970     // Balance anchor and cursor
971     SelBalance();
972  
973     int xo;
974     int yo;
975     cursor->p->GetXY(xo, yo);
976     int w = cursor->p->Width();
977     int x1;
978     int y1;
979     cursor->GetPos(x1, y1);
980     cursor->getAD(a1, d1);
981     int x;
982     int y;
983     anchor->GetPos(x, y);
984     anchor->getAD(a, d);
985
986     xpoint[i] = x;
987     ypoint[i++] = y + d;
988     xpoint[i] = x;
989     ypoint[i++] = y - a;
990     
991     if (y != y1) {
992             xpoint[i] = xo + w;
993             ypoint[i++] = y - a;
994
995             if (x1 < xo + w) {
996                     xpoint[i] = xo + w;
997                     ypoint[i++] = y1 - a;
998             }
999     }
1000
1001     xpoint[i] = x1;
1002     ypoint[i++] = y1 - a;
1003     xpoint[i] = x1;
1004     ypoint[i++] = y1 + d;
1005     
1006     if (y != y1) {
1007             xpoint[i] = xo;
1008             ypoint[i++] = y1 + d;
1009             if (x > xo) {
1010                     xpoint[i] = xo;
1011                     ypoint[i++] = y + d;
1012             }
1013     }
1014     xpoint[i] = xpoint[0];
1015     ypoint[i++] = ypoint[0];
1016
1017     *xp = &xpoint[0];
1018     *yp = &ypoint[0];
1019     np = i;
1020 //    lyxerr << "AN[" << x << " " << y << " " << x1 << " " << y1 << "] ";
1021 //    lyxerr << "MT[" << a << " " << d << " " << a1 << " " << d1 << "] ";
1022 //    for (i = 0; i < np; ++i)
1023 //      lyxerr << "XY[" << point[i].x << " " << point[i].y << "] ";
1024     
1025 }
1026
1027
1028 void MathedCursor::setAccent(int ac)
1029 {
1030         if (ac > 0 && accent < 8) {
1031                 nestaccent[accent++] = ac;
1032         } else
1033           accent = 0;  // consumed!
1034 }
1035
1036  
1037 int MathedCursor::getAccent() const
1038 {
1039         return (accent > 0) ? nestaccent[accent - 1]: 0;
1040 }
1041
1042
1043 void MathedCursor::doAccent(byte c, MathedTextCodes t)
1044 {
1045         MathedInset * ac = 0;
1046         
1047         for (int i = accent - 1; i >= 0; --i) {
1048                 if (i == accent - 1)
1049                   ac = new MathAccentInset(c, t, nestaccent[i]);
1050                 else 
1051                   ac = new MathAccentInset(ac, nestaccent[i]);
1052         }
1053         if (ac) 
1054           cursor->Insert(ac);
1055         
1056         accent = 0;  // consumed!
1057 }
1058
1059
1060 void MathedCursor::doAccent(MathedInset * p)
1061 {
1062         MathedInset * ac = 0;
1063         
1064         for (int i = accent - 1; i >= 0; --i) {
1065                 if (i == accent - 1)
1066                   ac = new MathAccentInset(p, nestaccent[i]);
1067                 else 
1068                   ac = new MathAccentInset(ac, nestaccent[i]);
1069         }
1070         if (ac) 
1071           cursor->Insert(ac);
1072         
1073         accent = 0;  // consumed!
1074 }
1075
1076
1077 void MathedCursor::toggleLastCode(MathedTextCodes t)
1078 {
1079         if (lastcode == t)
1080                 lastcode = LM_TC_VAR;
1081         else
1082                 lastcode = t;
1083 }