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