]> git.lyx.org Git - lyx.git/blob - src/mathed/math_nestinset.C
fix bug 1598 (crash on cursor up/down in script)
[lyx.git] / src / mathed / math_nestinset.C
1 /**
2  * \file math_nestinset.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "math_nestinset.h"
14
15 #include "math_arrayinset.h"
16 #include "math_braceinset.h"
17 #include "math_commentinset.h"
18 #include "math_data.h"
19 #include "math_deliminset.h"
20 #include "math_factory.h"
21 #include "math_hullinset.h"
22 #include "math_mathmlstream.h"
23 #include "math_macroarg.h"
24 #include "math_mboxinset.h"
25 #include "math_parser.h"
26 #include "math_scriptinset.h"
27 #include "math_spaceinset.h"
28 #include "math_symbolinset.h"
29 #include "math_support.h"
30 #include "math_unknowninset.h"
31
32 #include "BufferView.h"
33 #include "CutAndPaste.h"
34 #include "FuncStatus.h"
35 #include "LColor.h"
36 #include "bufferview_funcs.h"
37 #include "coordcache.h"
38 #include "cursor.h"
39 #include "debug.h"
40 #include "dispatchresult.h"
41 #include "funcrequest.h"
42 #include "gettext.h"
43 #include "outputparams.h"
44 #include "undo.h"
45
46 #include "support/lstrings.h"
47
48 #include "frontends/Dialogs.h"
49 #include "frontends/LyXView.h"
50 #include "frontends/Painter.h"
51
52 #include <sstream>
53
54 using lyx::cap::copySelection;
55 using lyx::cap::grabAndEraseSelection;
56 using lyx::cap::cutSelection;
57 using lyx::cap::pasteSelection;
58 using lyx::cap::replaceSelection;
59 using lyx::cap::selClearOrDel;
60
61 using std::endl;
62 using std::string;
63 using std::istringstream;
64
65
66
67 namespace {
68
69 // local global
70 int first_x;
71 int first_y;
72
73 } // namespace anon
74
75
76
77
78 MathNestInset::MathNestInset(idx_type nargs)
79         : cells_(nargs), lock_(false)
80 {}
81
82
83 MathInset::idx_type MathNestInset::nargs() const
84 {
85         return cells_.size();
86 }
87
88
89 MathArray & MathNestInset::cell(idx_type i)
90 {
91         return cells_[i];
92 }
93
94
95 MathArray const & MathNestInset::cell(idx_type i) const
96 {
97         return cells_[i];
98 }
99
100
101 void MathNestInset::getCursorPos(CursorSlice const & sl,
102         int & x, int & y) const
103 {
104 // FIXME: This is a hack. Ideally, the coord cache should not store
105 // absolute positions, but relative ones. This would mean to call
106 // setXY() not in MathArray::draw(), but in the parent insets' draw()
107 // with the correctly adjusted x,y values. But this means that we'd have
108 // to touch all (math)inset's draw() methods. Right now, we'll store
109 // absolute value, and make them here relative, only to make them
110 // absolute again when actually drawing the cursor. What a mess.
111         BOOST_ASSERT(ptr_cmp(&sl.inset(), this));
112         MathArray const & ar = sl.cell();
113         if (!theCoords.getArrays().has(&ar)) {
114                 // this can (semi-)legally happen if we just created this cell
115                 // and it never has been drawn before. So don't ASSERT.
116                 //lyxerr << "no cached data for array " << &ar << endl;
117                 x = 0;
118                 y = 0;
119                 return;
120         }
121         Point const pt = theCoords.getArrays().xy(&ar);
122         if (!theCoords.getInsets().has(this)) {
123                 // same as above
124                 //lyxerr << "no cached data for inset " << this << endl;
125                 x = 0;
126                 y = 0;
127                 return;
128         }
129         Point const pt2 = theCoords.getInsets().xy(this);
130         //lyxerr << "retrieving position cache for MathArray "
131         //      << pt.x_ << ' ' << pt.y_ << std::endl;
132         x = pt.x_ - pt2.x_ + ar.pos2x(sl.pos());
133         y = pt.y_ - pt2.y_;
134 //      lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
135 //              << " asc: " << ascent() << "  des: " << descent()
136 //              << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
137         // move cursor visually into empty cells ("blue rectangles");
138         if (ar.empty())
139                 x += 2;
140 }
141
142 void MathNestInset::metrics(MetricsInfo const & mi) const
143 {
144         MetricsInfo m = mi;
145         for (idx_type i = 0, n = nargs(); i != n; ++i)
146                 cell(i).metrics(m);
147 }
148
149
150 bool MathNestInset::idxNext(LCursor & cur) const
151 {
152         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
153         if (cur.idx() == cur.lastidx())
154                 return false;
155         ++cur.idx();
156         cur.pos() = 0;
157         return true;
158 }
159
160
161 bool MathNestInset::idxRight(LCursor & cur) const
162 {
163         return idxNext(cur);
164 }
165
166
167 bool MathNestInset::idxPrev(LCursor & cur) const
168 {
169         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
170         if (cur.idx() == 0)
171                 return false;
172         --cur.idx();
173         cur.pos() = cur.lastpos();
174         return true;
175 }
176
177
178 bool MathNestInset::idxLeft(LCursor & cur) const
179 {
180         return idxPrev(cur);
181 }
182
183
184 bool MathNestInset::idxFirst(LCursor & cur) const
185 {
186         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
187         if (nargs() == 0)
188                 return false;
189         cur.idx() = 0;
190         cur.pos() = 0;
191         return true;
192 }
193
194
195 bool MathNestInset::idxLast(LCursor & cur) const
196 {
197         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
198         if (nargs() == 0)
199                 return false;
200         cur.idx() = cur.lastidx();
201         cur.pos() = cur.lastpos();
202         return true;
203 }
204
205
206 void MathNestInset::dump() const
207 {
208         WriteStream os(lyxerr);
209         os << "---------------------------------------------\n";
210         write(os);
211         os << "\n";
212         for (idx_type i = 0, n = nargs(); i != n; ++i)
213                 os << cell(i) << "\n";
214         os << "---------------------------------------------\n";
215 }
216
217
218 void MathNestInset::draw(PainterInfo & pi, int x, int y) const
219 {
220 #if 0
221         if (lock_)
222                 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
223                                         LColor::mathlockbg);
224 #endif
225         setPosCache(pi, x, y);
226 }
227
228
229 void MathNestInset::drawSelection(PainterInfo & pi, int x, int y) const
230 {
231         // FIXME: hack to get position cache warm
232         draw(pi, x, y);
233
234         // this should use the x/y values given, not the cached values
235         LCursor & cur = pi.base.bv->cursor();
236         if (!cur.selection())
237                 return;
238         if (!ptr_cmp(&cur.inset(), this))
239                 return;
240
241         CursorSlice s1 = cur.selBegin();
242         CursorSlice s2 = cur.selEnd();
243         //lyxerr << "MathNestInset::drawing selection: "
244         //      << " s1: " << s1 << " s2: " << s2 << endl;
245         if (s1.idx() == s2.idx()) {
246                 MathArray const & c = cell(s1.idx());
247                 int x1 = c.xo() + c.pos2x(s1.pos());
248                 int y1 = c.yo() - c.ascent();
249                 int x2 = c.xo() + c.pos2x(s2.pos());
250                 int y2 = c.yo() + c.descent();
251                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
252         //lyxerr << "MathNestInset::drawing selection 3: "
253         //      << " x1: " << x1 << " x2: " << x2
254         //      << " y1: " << y1 << " y2: " << y2 << endl;
255         } else {
256                 for (idx_type i = 0; i < nargs(); ++i) {
257                         if (idxBetween(i, s1.idx(), s2.idx())) {
258                                 MathArray const & c = cell(i);
259                                 int x1 = c.xo();
260                                 int y1 = c.yo() - c.ascent();
261                                 int x2 = c.xo() + c.width();
262                                 int y2 = c.yo() + c.descent();
263                                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
264                         }
265                 }
266         }
267 }
268
269
270 void MathNestInset::validate(LaTeXFeatures & features) const
271 {
272         for (idx_type i = 0; i < nargs(); ++i)
273                 cell(i).validate(features);
274 }
275
276
277 void MathNestInset::replace(ReplaceData & rep)
278 {
279         for (idx_type i = 0; i < nargs(); ++i)
280                 cell(i).replace(rep);
281 }
282
283
284 bool MathNestInset::contains(MathArray const & ar) const
285 {
286         for (idx_type i = 0; i < nargs(); ++i)
287                 if (cell(i).contains(ar))
288                         return true;
289         return false;
290 }
291
292
293 bool MathNestInset::lock() const
294 {
295         return lock_;
296 }
297
298
299 void MathNestInset::lock(bool l)
300 {
301         lock_ = l;
302 }
303
304
305 bool MathNestInset::isActive() const
306 {
307         return nargs() > 0;
308 }
309
310
311 MathArray MathNestInset::glue() const
312 {
313         MathArray ar;
314         for (size_t i = 0; i < nargs(); ++i)
315                 ar.append(cell(i));
316         return ar;
317 }
318
319
320 void MathNestInset::write(WriteStream & os) const
321 {
322         os << '\\' << name().c_str();
323         for (size_t i = 0; i < nargs(); ++i)
324                 os << '{' << cell(i) << '}';
325         if (nargs() == 0)
326                 os.pendingSpace(true);
327         if (lock_ && !os.latex()) {
328                 os << "\\lyxlock";
329                 os.pendingSpace(true);
330         }
331 }
332
333
334 void MathNestInset::normalize(NormalStream & os) const
335 {
336         os << '[' << name().c_str();
337         for (size_t i = 0; i < nargs(); ++i)
338                 os << ' ' << cell(i);
339         os << ']';
340 }
341
342
343 int MathNestInset::latex(Buffer const &, std::ostream & os,
344                         OutputParams const & runparams) const
345 {
346         WriteStream wi(os, runparams.moving_arg, true);
347         write(wi);
348         return wi.line();
349 }
350
351
352 void MathNestInset::notifyCursorLeaves(LCursor & /*cur*/)
353 {
354 #ifdef WITH_WARNINGS
355 #warning look here
356 #endif
357 #if 0
358         MathArray & ar = cur.cell();
359         // remove base-only "scripts"
360         for (pos_type i = 0; i + 1 < ar.size(); ++i) {
361                 MathScriptInset * p = operator[](i).nucleus()->asScriptInset();
362                 if (p && p->nargs() == 1) {
363                         MathArray ar = p->nuc();
364                         erase(i);
365                         insert(i, ar);
366                         cur.adjust(i, ar.size() - 1);
367                 }
368         }
369
370         // glue adjacent font insets of the same kind
371         for (pos_type i = 0; i + 1 < size(); ++i) {
372                 MathFontInset * p = operator[](i).nucleus()->asFontInset();
373                 MathFontInset const * q = operator[](i + 1)->asFontInset();
374                 if (p && q && p->name() == q->name()) {
375                         p->cell(0).append(q->cell(0));
376                         erase(i + 1);
377                         cur.adjust(i, -1);
378                 }
379         }
380 #endif
381 }
382
383
384 void MathNestInset::handleFont
385         (LCursor & cur, string const & arg, string const & font)
386 {
387         // this whole function is a hack and won't work for incremental font
388         // changes...
389         recordUndo(cur, Undo::ATOMIC);
390
391         if (cur.inset().asMathInset()->name() == font)
392                 cur.handleFont(font);
393         else {
394                 cur.handleNest(createMathInset(font));
395                 cur.insert(arg);
396         }
397 }
398
399
400 void MathNestInset::handleFont2(LCursor & cur, string const & arg)
401 {
402         recordUndo(cur, Undo::ATOMIC);
403         LyXFont font;
404         bool b;
405         bv_funcs::string2font(arg, font, b);
406         if (font.color() != LColor::inherit) {
407                 MathAtom at = createMathInset("color");
408                 asArray(lcolor.getGUIName(font.color()), at.nucleus()->cell(0));
409                 cur.handleNest(at, 1);
410         }
411 }
412
413
414 void MathNestInset::doDispatch(LCursor & cur, FuncRequest & cmd)
415 {
416         //lyxerr << "MathNestInset: request: " << cmd << std::endl;
417         //CursorSlice sl = cur.current();
418
419         switch (cmd.action) {
420
421         case LFUN_PASTE: {
422                 recordUndo(cur);
423                 cur.message(_("Paste"));
424                 replaceSelection(cur);
425                 size_t n = 0;
426                 istringstream is(cmd.argument);
427                 is >> n;
428                 pasteSelection(cur, n);
429                 cur.clearSelection(); // bug 393
430                 cur.bv().switchKeyMap();
431                 finishUndo();
432                 break;
433         }
434
435         case LFUN_CUT:
436                 cutSelection(cur, true, true);
437                 cur.message(_("Cut"));
438                 break;
439
440         case LFUN_COPY:
441                 copySelection(cur);
442                 cur.message(_("Copy"));
443                 break;
444
445         case LFUN_MOUSE_PRESS:
446                 lfunMousePress(cur, cmd);
447                 break;
448
449         case LFUN_MOUSE_MOTION:
450                 lfunMouseMotion(cur, cmd);
451                 break;
452
453         case LFUN_MOUSE_RELEASE:
454                 lfunMouseRelease(cur, cmd);
455                 break;
456
457         case LFUN_FINISHED_LEFT:
458                 cur.bv().cursor() = cur;
459                 break;
460
461         case LFUN_FINISHED_RIGHT:
462                 ++cur.pos();
463                 cur.bv().cursor() = cur;
464                 break;
465
466         case LFUN_FINISHED_UP:
467                 cur.bv().cursor() = cur;
468                 break;
469
470         case LFUN_FINISHED_DOWN:
471                 cur.bv().cursor() = cur;
472                 break;
473
474         case LFUN_RIGHTSEL:
475         case LFUN_RIGHT:
476                 cur.selHandle(cmd.action == LFUN_RIGHTSEL);
477                 cur.autocorrect() = false;
478                 cur.clearTargetX();
479                 cur.macroModeClose();
480                 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
481                         cur.pushLeft(*cur.nextAtom().nucleus());
482                         cur.inset().idxFirst(cur);
483                 } else if (cur.posRight() || idxRight(cur)
484                         || cur.popRight() || cur.selection())
485                         ;
486                 else
487                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
488                 break;
489
490         case LFUN_LEFTSEL:
491         case LFUN_LEFT:
492                 cur.selHandle(cmd.action == LFUN_LEFTSEL);
493                 cur.autocorrect() = false;
494                 cur.clearTargetX();
495                 cur.macroModeClose();
496                 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
497                         cur.posLeft();
498                         cur.push(*cur.nextAtom().nucleus());
499                         cur.inset().idxLast(cur);
500                 } else if (cur.posLeft() || idxLeft(cur)
501                         || cur.popLeft() || cur.selection())
502                         ;
503                 else
504                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
505                 break;
506
507         case LFUN_UPSEL:
508         case LFUN_UP:
509                 cur.selHandle(cmd.action == LFUN_UPSEL);
510                 if (!cur.up())
511                         cmd = FuncRequest(LFUN_FINISHED_UP);
512                 // fixes bug 1598. Please check!
513                 cur.normalize();
514                 break;
515
516         case LFUN_DOWNSEL:
517         case LFUN_DOWN:
518                 cur.selHandle(cmd.action == LFUN_DOWNSEL);
519                 if (!cur.down())
520                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
521                 // fixes bug 1598. Please check!
522                 cur.normalize();
523                 break;
524
525         case LFUN_MOUSE_DOUBLE:
526         case LFUN_MOUSE_TRIPLE:
527         case LFUN_WORDSEL:
528                 cur.pos() = 0;
529                 cur.idx() = 0;
530                 cur.resetAnchor();
531                 cur.selection() = true;
532                 cur.pos() = cur.lastpos();
533                 cur.idx() = cur.lastidx();
534                 break;
535
536         case LFUN_UP_PARAGRAPHSEL:
537         case LFUN_UP_PARAGRAPH:
538         case LFUN_DOWN_PARAGRAPHSEL:
539         case LFUN_DOWN_PARAGRAPH:
540                 break;
541
542         case LFUN_HOMESEL:
543         case LFUN_HOME:
544         case LFUN_WORDLEFTSEL:
545         case LFUN_WORDLEFT:
546                 cur.selHandle(cmd.action == LFUN_WORDLEFTSEL || cmd.action == LFUN_HOMESEL);
547                 cur.macroModeClose();
548                 if (cur.pos() != 0) {
549                         cur.pos() = 0;
550                 } else if (cur.col() != 0) {
551                         cur.idx() -= cur.col();
552                         cur.pos() = 0;
553                 } else if (cur.idx() != 0) {
554                         cur.idx() = 0;
555                         cur.pos() = 0;
556                 } else {
557                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
558                 }
559                 break;
560
561         case LFUN_WORDRIGHTSEL:
562         case LFUN_WORDRIGHT:
563         case LFUN_ENDSEL:
564         case LFUN_END:
565                 cur.selHandle(cmd.action == LFUN_WORDRIGHTSEL || cmd.action == LFUN_ENDSEL);
566                 cur.macroModeClose();
567                 cur.clearTargetX();
568                 if (cur.pos() != cur.lastpos()) {
569                         cur.pos() = cur.lastpos();
570                 } else if (cur.col() != cur.lastcol()) {
571                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
572                         cur.pos() = cur.lastpos();
573                 } else if (cur.idx() != cur.lastidx()) {
574                         cur.idx() = cur.lastidx();
575                         cur.pos() = cur.lastpos();
576                 } else {
577                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
578                 }
579                 break;
580
581         case LFUN_PRIORSEL:
582         case LFUN_PRIOR:
583                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
584                 break;
585
586         case LFUN_NEXTSEL:
587         case LFUN_NEXT:
588                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
589                 break;
590
591         case LFUN_CELL_FORWARD:
592                 cur.inset().idxNext(cur);
593                 break;
594
595         case LFUN_CELL_BACKWARD:
596                 cur.inset().idxPrev(cur);
597                 break;
598
599         case LFUN_DELETE_WORD_BACKWARD:
600         case LFUN_BACKSPACE:
601                 recordUndo(cur, Undo::ATOMIC);
602                 cur.backspace();
603                 break;
604
605         case LFUN_DELETE_WORD_FORWARD:
606         case LFUN_DELETE:
607                 recordUndo(cur);
608                 cur.erase();
609                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
610                 break;
611
612         case LFUN_ESCAPE:
613                 if (cur.selection())
614                         cur.clearSelection();
615                 else
616                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
617                 break;
618
619         case LFUN_INSET_TOGGLE:
620                 recordUndo(cur);
621                 //lockToggle();
622                 if (cur.pos() != cur.lastpos()) {
623                         // toggle previous inset ...
624                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
625                 } else if (cur.popLeft() && cur.pos() != cur.lastpos()) {
626                         // ... or enclosing inset if we are in the last inset position
627                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
628                         ++cur.pos();
629                 }
630                 break;
631
632         case LFUN_SELFINSERT:
633                 recordUndo(cur);
634                 if (cmd.argument.size() != 1) {
635                         cur.insert(cmd.argument);
636                         break;
637                 }
638                 if (!interpret(cur, cmd.argument[0]))
639                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
640                 break;
641
642         //case LFUN_GETXY:
643         //      sprintf(dispatch_buffer, "%d %d",);
644         //      break;
645
646         case LFUN_SETXY: {
647                 lyxerr << "LFUN_SETXY broken!" << endl;
648                 int x = 0;
649                 int y = 0;
650                 istringstream is(cmd.argument);
651                 is >> x >> y;
652                 cur.setScreenPos(x, y);
653                 break;
654         }
655
656         // Special casing for superscript in case of LyX handling
657         // dead-keys:
658         case LFUN_CIRCUMFLEX:
659                 if (cmd.argument.empty()) {
660                         // do superscript if LyX handles
661                         // deadkeys
662                         recordUndo(cur, Undo::ATOMIC);
663                         script(cur, true);
664                 }
665                 break;
666
667         case LFUN_UMLAUT:
668         case LFUN_ACUTE:
669         case LFUN_GRAVE:
670         case LFUN_BREVE:
671         case LFUN_DOT:
672         case LFUN_MACRON:
673         case LFUN_CARON:
674         case LFUN_TILDE:
675         case LFUN_CEDILLA:
676         case LFUN_CIRCLE:
677         case LFUN_UNDERDOT:
678         case LFUN_TIE:
679         case LFUN_OGONEK:
680         case LFUN_HUNG_UMLAUT:
681                 break;
682
683         //  Math fonts
684         case LFUN_FREEFONT_APPLY:
685         case LFUN_FREEFONT_UPDATE:
686                 handleFont2(cur, cmd.argument);
687                 break;
688
689         case LFUN_BOLD:
690                 handleFont(cur, cmd.argument, "mathbf");
691                 break;
692         case LFUN_SANS:
693                 handleFont(cur, cmd.argument, "mathsf");
694                 break;
695         case LFUN_EMPH:
696                 handleFont(cur, cmd.argument, "mathcal");
697                 break;
698         case LFUN_ROMAN:
699                 handleFont(cur, cmd.argument, "mathrm");
700                 break;
701         case LFUN_CODE:
702                 handleFont(cur, cmd.argument, "texttt");
703                 break;
704         case LFUN_FRAK:
705                 handleFont(cur, cmd.argument, "mathfrak");
706                 break;
707         case LFUN_ITAL:
708                 handleFont(cur, cmd.argument, "mathit");
709                 break;
710         case LFUN_NOUN:
711                 handleFont(cur, cmd.argument, "mathbb");
712                 break;
713         //case LFUN_FREEFONT_APPLY:
714                 handleFont(cur, cmd.argument, "textrm");
715                 break;
716         case LFUN_DEFAULT:
717                 handleFont(cur, cmd.argument, "textnormal");
718                 break;
719
720         case LFUN_MATH_MODE:
721 #if 1
722                 // ignore math-mode on when already in math mode
723                 if (currentMode() == InsetBase::MATH_MODE && cmd.argument == "on")
724                         break;
725                 cur.macroModeClose();
726                 selClearOrDel(cur);
727                 cur.plainInsert(MathAtom(new MathMBoxInset(cur.bv())));
728                 cur.posLeft();
729                 cur.pushLeft(*cur.nextInset());
730 #else
731                 if (currentMode() == InsetBase::TEXT_MODE) {
732                         cur.niceInsert(MathAtom(new MathHullInset("simple")));
733                         cur.message(_("create new math text environment ($...$)"));
734                 } else {
735                         handleFont(cur, cmd.argument, "textrm");
736                         cur.message(_("entered math text mode (textrm)"));
737                 }
738 #endif
739                 break;
740
741         case LFUN_MATH_SIZE:
742 #if 0
743                 recordUndo(cur);
744                 cur.setSize(arg);
745 #endif
746                 break;
747
748         case LFUN_INSERT_MATRIX: {
749                 recordUndo(cur, Undo::ATOMIC);
750                 unsigned int m = 1;
751                 unsigned int n = 1;
752                 string v_align;
753                 string h_align;
754                 istringstream is(cmd.argument);
755                 is >> m >> n >> v_align >> h_align;
756                 if (m < 1)
757                         m = 1;
758                 if (n < 1)
759                         n = 1;
760                 v_align += 'c';
761                 cur.niceInsert(
762                         MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
763                 break;
764         }
765
766         case LFUN_MATH_DELIM: {
767                 lyxerr << "MathNestInset::LFUN_MATH_DELIM" << endl;
768                 string ls;
769                 string rs = lyx::support::split(cmd.argument, ls, ' ');
770                 // Reasonable default values
771                 if (ls.empty())
772                         ls = '(';
773                 if (rs.empty())
774                         rs = ')';
775                 recordUndo(cur, Undo::ATOMIC);
776                 cur.handleNest(MathAtom(new MathDelimInset(ls, rs)));
777                 break;
778         }
779
780         case LFUN_SPACE_INSERT:
781         case LFUN_MATH_SPACE:
782                 recordUndo(cur, Undo::ATOMIC);
783                 cur.insert(MathAtom(new MathSpaceInset(",")));
784                 break;
785
786         case LFUN_INSET_ERT:
787                 // interpret this as if a backslash was typed
788                 recordUndo(cur, Undo::ATOMIC);
789                 interpret(cur, '\\');
790                 break;
791
792         case LFUN_SUBSCRIPT:
793                 // interpret this as if a _ was typed
794                 recordUndo(cur, Undo::ATOMIC);
795                 interpret(cur, '_');
796                 break;
797
798         case LFUN_SUPERSCRIPT:
799                 // interpret this as if a ^ was typed
800                 recordUndo(cur, Undo::ATOMIC);
801                 interpret(cur, '^');
802                 break;
803
804 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
805 // handling such that "self-insert" works on "arbitrary stuff" too, and
806 // math-insert only handles special math things like "matrix".
807         case LFUN_INSERT_MATH:
808                 recordUndo(cur, Undo::ATOMIC);
809                 cur.niceInsert(cmd.argument);
810                 break;
811
812         case LFUN_DIALOG_SHOW_NEW_INSET: {
813                 string const & name = cmd.argument;
814                 string data;
815 #if 0
816                 if (name == "ref") {
817                         RefInset tmp(name);
818                         data = tmp.createDialogStr(name);
819                 }
820 #endif
821                 cur.bv().owner()->getDialogs().show(name, data, 0);
822                 break;
823         }
824
825         case LFUN_INSET_APPLY: {
826                 string const name = cmd.getArg(0);
827                 InsetBase * base = cur.bv().owner()->getDialogs().getOpenInset(name);
828
829                 if (base) {
830                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument);
831                         base->dispatch(cur, fr);
832                         break;
833                 }
834                 MathArray ar;
835                 if (createMathInset_fromDialogStr(cmd.argument, ar)) {
836                         cur.insert(ar);
837                         break;
838                 }
839                 cur.undispatched();
840                 break;
841         }
842
843         default:
844                 MathDimInset::doDispatch(cur, cmd);
845                 break;
846         }
847 }
848
849
850 bool MathNestInset::getStatus(LCursor & /*cur*/, FuncRequest const & cmd,
851                 FuncStatus & flag) const
852 {
853         // the font related toggles
854         //string tc = "mathnormal";
855         bool ret = true;
856         switch (cmd.action) {
857 #if 0
858         case LFUN_TABULAR_FEATURE:
859                 // FIXME: check temporarily disabled
860                 // valign code
861                 char align = mathcursor::valign();
862                 if (align == '\0') {
863                         enable = false;
864                         break;
865                 }
866                 if (cmd.argument.empty()) {
867                         flag.clear();
868                         break;
869                 }
870                 if (!contains("tcb", cmd.argument[0])) {
871                         enable = false;
872                         break;
873                 }
874                 flag.setOnOff(cmd.argument[0] == align);
875                 break;
876         case LFUN_BOLD:
877                 flag.setOnOff(tc == "mathbf");
878                 break;
879         case LFUN_SANS:
880                 flag.setOnOff(tc == "mathsf");
881                 break;
882         case LFUN_EMPH:
883                 flag.setOnOff(tc == "mathcal");
884                 break;
885         case LFUN_ROMAN:
886                 flag.setOnOff(tc == "mathrm");
887                 break;
888         case LFUN_CODE:
889                 flag.setOnOff(tc == "mathtt");
890                 break;
891         case LFUN_NOUN:
892                 flag.setOnOff(tc == "mathbb");
893                 break;
894         case LFUN_DEFAULT:
895                 flag.setOnOff(tc == "mathnormal");
896                 break;
897 #endif
898         case LFUN_MATH_MUTATE:
899                 //flag.setOnOff(mathcursor::formula()->hullType() == cmd.argument);
900                 flag.setOnOff(false);
901                 break;
902
903         // we just need to be in math mode to enable that
904         case LFUN_MATH_SIZE:
905         case LFUN_MATH_SPACE:
906         case LFUN_MATH_LIMITS:
907         case LFUN_MATH_NONUMBER:
908         case LFUN_MATH_NUMBER:
909         case LFUN_MATH_EXTERN:
910                 flag.enabled(true);
911                 break;
912
913         default:
914                 ret = false;
915                 break;
916         }
917         return ret;
918 }
919
920
921 void MathNestInset::edit(LCursor & cur, bool left)
922 {
923         cur.push(*this);
924         cur.idx() = left ? 0 : cur.lastidx();
925         cur.pos() = left ? 0 : cur.lastpos();
926         cur.resetAnchor();
927         lyxerr << "MathNestInset::edit, cur:\n" << cur << endl;
928 }
929
930
931 InsetBase * MathNestInset::editXY(LCursor & cur, int x, int y) const
932 {
933         int idx_min = 0;
934         int dist_min = 1000000;
935         for (idx_type i = 0; i < nargs(); ++i) {
936                 int d = cell(i).dist(x, y);
937                 if (d < dist_min) {
938                         dist_min = d;
939                         idx_min = i;
940                 }
941         }
942         MathArray const & ar = cell(idx_min);
943         cur.push(const_cast<MathNestInset&>(*this));
944         cur.idx() = idx_min;
945         cur.pos() = ar.x2pos(x - ar.xo());
946         lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
947         if (dist_min == 0) {
948                 // hit inside cell
949                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
950                         if (ar[i]->covers(x, y))
951                                 return ar[i].nucleus()->editXY(cur, x, y);
952         }
953         return const_cast<MathNestInset*>(this);
954 }
955
956
957 void MathNestInset::lfunMousePress(LCursor & cur, FuncRequest & cmd)
958 {
959         lyxerr << "lfunMousePress: buttons: " << cmd.button() << endl;
960         if (cmd.button() == mouse_button::button1) {
961                 first_x = cmd.x;
962                 first_y = cmd.y;
963                 lyxerr << "lfunMousePress: setting cursor to: " << cur << endl;
964                 cur.resetAnchor();
965                 cur.bv().cursor() = cur;
966         }
967
968         if (cmd.button() == mouse_button::button2) {
969                 cur.dispatch(FuncRequest(LFUN_PASTESELECTION));
970         }
971 }
972
973
974 void MathNestInset::lfunMouseMotion(LCursor & cur, FuncRequest & cmd)
975 {
976         // only select with button 1
977         if (cmd.button() == mouse_button::button1) {
978                 LCursor & bvcur = cur.bv().cursor();
979                 if (abs(cmd.x - first_x) + abs(cmd.y - first_y) > 4
980                     && bvcur.anchor_.hasPart(cur)) {
981                         first_x = cmd.x;
982                         first_y = cmd.y;
983
984                         bvcur.setCursor(cur);
985                         bvcur.selection() = true;
986                 } else
987                         cur.undispatched();
988         }
989 }
990
991
992 void MathNestInset::lfunMouseRelease(LCursor & cur, FuncRequest & cmd)
993 {
994         lyxerr << "lfunMouseRelease: buttons: " << cmd.button() << endl;
995
996         if (cmd.button() == mouse_button::button1) {
997                 //cur.bv().stuffClipboard(cur.grabSelection());
998                 return;
999         }
1000
1001         if (cmd.button() == mouse_button::button2) {
1002                 MathArray ar;
1003                 asArray(cur.bv().getClipboard(), ar);
1004                 cur.clearSelection();
1005                 cur.setScreenPos(cmd.x, cmd.y);
1006                 cur.insert(ar);
1007                 cur.bv().update();
1008                 return;
1009         }
1010
1011         if (cmd.button() == mouse_button::button3) {
1012                 // try to dispatch to enclosed insets first
1013                 cur.bv().owner()->getDialogs().show("mathpanel");
1014                 return;
1015         }
1016
1017         cur.undispatched();
1018 }
1019
1020
1021 bool MathNestInset::interpret(LCursor & cur, char c)
1022 {
1023         lyxerr << "interpret 2: '" << c << "'" << endl;
1024         cur.clearTargetX();
1025
1026         // handle macroMode
1027         if (cur.inMacroMode()) {
1028                 string name = cur.macroName();
1029
1030                 /// are we currently typing '#1' or '#2' or...?
1031                 if (name == "\\#") {
1032                         cur.backspace();
1033                         int n = c - '0';
1034                         if (n >= 1 && n <= 9)
1035                                 cur.insert(new MathMacroArgument(n));
1036                         return true;
1037                 }
1038
1039                 if (isalpha(c)) {
1040                         cur.activeMacro()->setName(name + c);
1041                         return true;
1042                 }
1043
1044                 // handle 'special char' macros
1045                 if (name == "\\") {
1046                         // remove the '\\'
1047                         if (c == '\\') {
1048                                 cur.backspace();
1049                                 if (currentMode() == MathInset::TEXT_MODE)
1050                                         cur.niceInsert(createMathInset("textbackslash"));
1051                                 else
1052                                         cur.niceInsert(createMathInset("backslash"));
1053                         } else if (c == '{') {
1054                                 cur.backspace();
1055                                 cur.niceInsert(MathAtom(new MathBraceInset));
1056                         } else if (c == '%') {
1057                                 cur.backspace();
1058                                 cur.niceInsert(MathAtom(new MathCommentInset));
1059                         } else if (c == '#') {
1060                                 BOOST_ASSERT(cur.activeMacro());
1061                                 cur.activeMacro()->setName(name + c);
1062                         } else {
1063                                 cur.backspace();
1064                                 cur.niceInsert(createMathInset(string(1, c)));
1065                         }
1066                         return true;
1067                 }
1068
1069                 // leave macro mode and try again if necessary
1070                 cur.macroModeClose();
1071                 if (c == '{')
1072                         cur.niceInsert(MathAtom(new MathBraceInset));
1073                 else if (c != ' ')
1074                         interpret(cur, c);
1075                 return true;
1076         }
1077
1078         // This is annoying as one has to press <space> far too often.
1079         // Disable it.
1080
1081 #if 0
1082                 // leave autocorrect mode if necessary
1083                 if (autocorrect() && c == ' ') {
1084                         autocorrect() = false;
1085                         return true;
1086                 }
1087 #endif
1088
1089         // just clear selection on pressing the space bar
1090         if (cur.selection() && c == ' ') {
1091                 cur.selection() = false;
1092                 return true;
1093         }
1094
1095         selClearOrDel(cur);
1096
1097         if (c == '\\') {
1098                 //lyxerr << "starting with macro" << endl;
1099                 cur.insert(MathAtom(new MathUnknownInset("\\", false)));
1100                 return true;
1101         }
1102
1103         if (c == '\n') {
1104                 if (currentMode() == MathInset::TEXT_MODE)
1105                         cur.insert(c);
1106                 return true;
1107         }
1108
1109         if (c == ' ') {
1110                 if (currentMode() == MathInset::TEXT_MODE) {
1111                         // insert spaces in text mode,
1112                         // but suppress direct insertion of two spaces in a row
1113                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1114                         // it is better than nothing...
1115                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ')
1116                                 cur.insert(c);
1117                         return true;
1118                 }
1119                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1120                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1121                         return true;
1122                 }
1123                 if (cur.popRight())
1124                         return true;
1125                 // if are at the very end, leave the formula
1126                 return cur.pos() != cur.lastpos();
1127         }
1128
1129         if (c == '_') {
1130                 script(cur, false);
1131                 return true;
1132         }
1133
1134         if (c == '^') {
1135                 script(cur, true);
1136                 return true;
1137         }
1138
1139         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' || c == '%') {
1140                 cur.niceInsert(createMathInset(string(1, c)));
1141                 return true;
1142         }
1143
1144         if (c == '~') {
1145                 cur.niceInsert(createMathInset("sim"));
1146                 return true;
1147         }
1148
1149         // try auto-correction
1150         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1151         //      return true;
1152
1153         // no special circumstances, so insert the character without any fuss
1154         cur.insert(c);
1155         cur.autocorrect() = true;
1156         return true;
1157 }
1158
1159
1160 bool MathNestInset::script(LCursor & cur, bool up)
1161 {
1162         // Hack to get \^ and \_ working
1163         lyxerr << "handling script: up: " << up << endl;
1164         if (cur.inMacroMode() && cur.macroName() == "\\") {
1165                 if (up)
1166                         cur.niceInsert(createMathInset("mathcircumflex"));
1167                 else
1168                         interpret(cur, '_');
1169                 return true;
1170         }
1171
1172         cur.macroModeClose();
1173         string safe = grabAndEraseSelection(cur);
1174         if (asScriptInset() && cur.idx() == 0) {
1175                 // we are in a nucleus of a script inset, move to _our_ script
1176                 MathScriptInset * inset = asScriptInset();
1177                 lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1178                 inset->ensure(up);
1179                 cur.idx() = inset->idxOfScript(up);
1180                 cur.pos() = 0;
1181         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1182                 --cur.pos();
1183                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1184                 cur.push(*inset);
1185                 cur.idx() = inset->idxOfScript(up);
1186                 cur.pos() = cur.lastpos();
1187         } else {
1188                 // convert the thing to our left to a scriptinset or create a new
1189                 // one if in the very first position of the array
1190                 if (cur.pos() == 0) {
1191                         lyxerr << "new scriptinset" << endl;
1192                         cur.insert(new MathScriptInset(up));
1193                 } else {
1194                         lyxerr << "converting prev atom " << endl;
1195                         cur.prevAtom() = MathAtom(new MathScriptInset(cur.prevAtom(), up));
1196                 }
1197                 --cur.pos();
1198                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1199                 cur.push(*inset);
1200                 cur.idx() = 1;
1201                 cur.pos() = 0;
1202         }
1203         lyxerr << "pasting 1: safe:\n" << safe << endl;
1204         cur.paste(safe);
1205         cur.resetAnchor();
1206         lyxerr << "pasting 2: safe:\n" << safe << endl;
1207         return true;
1208 }