]> git.lyx.org Git - lyx.git/blob - src/mathed/math_nestinset.C
get rid of broken_header.h and some unneeded tests
[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.arrays_.has(&ar)) {
114                 // this can (semi-)legally happen if we jsut 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.arrays_.xy(&ar);
122         if (!theCoords.insets_.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.insets_.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                 break;
513
514         case LFUN_DOWNSEL:
515         case LFUN_DOWN:
516                 cur.selHandle(cmd.action == LFUN_DOWNSEL);
517                 if (!cur.down())
518                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
519                 break;
520
521         case LFUN_MOUSE_DOUBLE:
522         case LFUN_MOUSE_TRIPLE:
523         case LFUN_WORDSEL:
524                 cur.pos() = 0;
525                 cur.idx() = 0;
526                 cur.resetAnchor();
527                 cur.selection() = true;
528                 cur.pos() = cur.lastpos();
529                 cur.idx() = cur.lastidx();
530                 break;
531
532         case LFUN_UP_PARAGRAPHSEL:
533         case LFUN_UP_PARAGRAPH:
534         case LFUN_DOWN_PARAGRAPHSEL:
535         case LFUN_DOWN_PARAGRAPH:
536                 break;
537
538         case LFUN_HOMESEL:
539         case LFUN_HOME:
540         case LFUN_WORDLEFTSEL:
541         case LFUN_WORDLEFT:
542                 cur.selHandle(cmd.action == LFUN_WORDLEFTSEL || cmd.action == LFUN_HOMESEL);
543                 cur.macroModeClose();
544                 if (cur.pos() != 0) {
545                         cur.pos() = 0;
546                 } else if (cur.col() != 0) {
547                         cur.idx() -= cur.col();
548                         cur.pos() = 0;
549                 } else if (cur.idx() != 0) {
550                         cur.idx() = 0;
551                         cur.pos() = 0;
552                 } else {
553                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
554                 }
555                 break;
556
557         case LFUN_WORDRIGHTSEL:
558         case LFUN_WORDRIGHT:
559         case LFUN_ENDSEL:
560         case LFUN_END:
561                 cur.selHandle(cmd.action == LFUN_WORDRIGHTSEL || cmd.action == LFUN_ENDSEL);
562                 cur.macroModeClose();
563                 cur.clearTargetX();
564                 if (cur.pos() != cur.lastpos()) {
565                         cur.pos() = cur.lastpos();
566                 } else if (cur.col() != cur.lastcol()) {
567                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
568                         cur.pos() = cur.lastpos();
569                 } else if (cur.idx() != cur.lastidx()) {
570                         cur.idx() = cur.lastidx();
571                         cur.pos() = cur.lastpos();
572                 } else {
573                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
574                 }
575                 break;
576
577         case LFUN_PRIORSEL:
578         case LFUN_PRIOR:
579                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
580                 break;
581
582         case LFUN_NEXTSEL:
583         case LFUN_NEXT:
584                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
585                 break;
586
587         case LFUN_CELL_FORWARD:
588                 cur.inset().idxNext(cur);
589                 break;
590
591         case LFUN_CELL_BACKWARD:
592                 cur.inset().idxPrev(cur);
593                 break;
594
595         case LFUN_DELETE_WORD_BACKWARD:
596         case LFUN_BACKSPACE:
597                 recordUndo(cur, Undo::ATOMIC);
598                 cur.backspace();
599                 break;
600
601         case LFUN_DELETE_WORD_FORWARD:
602         case LFUN_DELETE:
603                 recordUndo(cur);
604                 cur.erase();
605                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
606                 break;
607
608         case LFUN_ESCAPE:
609                 if (cur.selection())
610                         cur.clearSelection();
611                 else
612                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
613                 break;
614
615         case LFUN_INSET_TOGGLE:
616                 recordUndo(cur);
617                 //lockToggle();
618                 if (cur.pos() != cur.lastpos()) {
619                         // toggle previous inset ...
620                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
621                 } else if (cur.popLeft() && cur.pos() != cur.lastpos()) {
622                         // ... or enclosing inset if we are in the last inset position
623                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
624                         ++cur.pos();
625                 }
626                 break;
627
628         case LFUN_SELFINSERT:
629                 recordUndo(cur);
630                 if (cmd.argument.size() != 1) {
631                         cur.insert(cmd.argument);
632                         break;
633                 }
634                 if (!interpret(cur, cmd.argument[0]))
635                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
636                 break;
637
638         //case LFUN_GETXY:
639         //      sprintf(dispatch_buffer, "%d %d",);
640         //      break;
641
642         case LFUN_SETXY: {
643                 lyxerr << "LFUN_SETXY broken!" << endl;
644                 int x = 0;
645                 int y = 0;
646                 istringstream is(cmd.argument);
647                 is >> x >> y;
648                 cur.setScreenPos(x, y);
649                 break;
650         }
651
652         // Special casing for superscript in case of LyX handling
653         // dead-keys:
654         case LFUN_CIRCUMFLEX:
655                 if (cmd.argument.empty()) {
656                         // do superscript if LyX handles
657                         // deadkeys
658                         recordUndo(cur, Undo::ATOMIC);
659                         script(cur, true);
660                 }
661                 break;
662
663         case LFUN_UMLAUT:
664         case LFUN_ACUTE:
665         case LFUN_GRAVE:
666         case LFUN_BREVE:
667         case LFUN_DOT:
668         case LFUN_MACRON:
669         case LFUN_CARON:
670         case LFUN_TILDE:
671         case LFUN_CEDILLA:
672         case LFUN_CIRCLE:
673         case LFUN_UNDERDOT:
674         case LFUN_TIE:
675         case LFUN_OGONEK:
676         case LFUN_HUNG_UMLAUT:
677                 break;
678
679         //  Math fonts
680         case LFUN_FREEFONT_APPLY:
681         case LFUN_FREEFONT_UPDATE:
682                 handleFont2(cur, cmd.argument);
683                 break;
684
685         case LFUN_BOLD:
686                 handleFont(cur, cmd.argument, "mathbf");
687                 break;
688         case LFUN_SANS:
689                 handleFont(cur, cmd.argument, "mathsf");
690                 break;
691         case LFUN_EMPH:
692                 handleFont(cur, cmd.argument, "mathcal");
693                 break;
694         case LFUN_ROMAN:
695                 handleFont(cur, cmd.argument, "mathrm");
696                 break;
697         case LFUN_CODE:
698                 handleFont(cur, cmd.argument, "texttt");
699                 break;
700         case LFUN_FRAK:
701                 handleFont(cur, cmd.argument, "mathfrak");
702                 break;
703         case LFUN_ITAL:
704                 handleFont(cur, cmd.argument, "mathit");
705                 break;
706         case LFUN_NOUN:
707                 handleFont(cur, cmd.argument, "mathbb");
708                 break;
709         //case LFUN_FREEFONT_APPLY:
710                 handleFont(cur, cmd.argument, "textrm");
711                 break;
712         case LFUN_DEFAULT:
713                 handleFont(cur, cmd.argument, "textnormal");
714                 break;
715
716         case LFUN_MATH_MODE:
717 #if 1
718                 // ignore math-mode on when already in math mode
719                 if (currentMode() == InsetBase::MATH_MODE && cmd.argument == "on")
720                         break;
721                 cur.macroModeClose();
722                 selClearOrDel(cur);
723                 cur.plainInsert(MathAtom(new MathMBoxInset(cur.bv())));
724                 cur.posLeft();
725                 cur.pushLeft(*cur.nextInset());
726 #else
727                 if (currentMode() == InsetBase::TEXT_MODE) {
728                         cur.niceInsert(MathAtom(new MathHullInset("simple")));
729                         cur.message(_("create new math text environment ($...$)"));
730                 } else {
731                         handleFont(cur, cmd.argument, "textrm");
732                         cur.message(_("entered math text mode (textrm)"));
733                 }
734 #endif
735                 break;
736
737         case LFUN_MATH_SIZE:
738 #if 0
739                 recordUndo(cur);
740                 cur.setSize(arg);
741 #endif
742                 break;
743
744         case LFUN_INSERT_MATRIX: {
745                 recordUndo(cur, Undo::ATOMIC);
746                 unsigned int m = 1;
747                 unsigned int n = 1;
748                 string v_align;
749                 string h_align;
750                 istringstream is(cmd.argument);
751                 is >> m >> n >> v_align >> h_align;
752                 if (m < 1)
753                         m = 1;
754                 if (n < 1)
755                         n = 1;
756                 v_align += 'c';
757                 cur.niceInsert(
758                         MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
759                 break;
760         }
761
762         case LFUN_MATH_DELIM: {
763                 lyxerr << "MathNestInset::LFUN_MATH_DELIM" << endl;
764                 string ls;
765                 string rs = lyx::support::split(cmd.argument, ls, ' ');
766                 // Reasonable default values
767                 if (ls.empty())
768                         ls = '(';
769                 if (rs.empty())
770                         rs = ')';
771                 recordUndo(cur, Undo::ATOMIC);
772                 cur.handleNest(MathAtom(new MathDelimInset(ls, rs)));
773                 break;
774         }
775
776         case LFUN_SPACE_INSERT:
777         case LFUN_MATH_SPACE:
778                 recordUndo(cur, Undo::ATOMIC);
779                 cur.insert(MathAtom(new MathSpaceInset(",")));
780                 break;
781
782         case LFUN_INSET_ERT:
783                 // interpret this as if a backslash was typed
784                 recordUndo(cur, Undo::ATOMIC);
785                 interpret(cur, '\\');
786                 break;
787
788 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
789 // handling such that "self-insert" works on "arbitrary stuff" too, and
790 // math-insert only handles special math things like "matrix".
791         case LFUN_INSERT_MATH:
792                 recordUndo(cur, Undo::ATOMIC);
793                 cur.niceInsert(cmd.argument);
794                 break;
795
796         case LFUN_DIALOG_SHOW_NEW_INSET: {
797                 string const & name = cmd.argument;
798                 string data;
799 #if 0
800                 if (name == "ref") {
801                         RefInset tmp(name);
802                         data = tmp.createDialogStr(name);
803                 }
804 #endif
805                 cur.bv().owner()->getDialogs().show(name, data, 0);
806                 break;
807         }
808
809         case LFUN_INSET_APPLY: {
810                 string const name = cmd.getArg(0);
811                 InsetBase * base = cur.bv().owner()->getDialogs().getOpenInset(name);
812
813                 if (base) {
814                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument);
815                         base->dispatch(cur, fr);
816                         break;
817                 }
818                 MathArray ar;
819                 if (createMathInset_fromDialogStr(cmd.argument, ar)) {
820                         cur.insert(ar);
821                         break;
822                 }
823                 cur.undispatched();
824                 break;
825         }
826
827         default:
828                 MathDimInset::doDispatch(cur, cmd);
829                 break;
830         }
831 }
832
833
834 bool MathNestInset::getStatus(LCursor & /*cur*/, FuncRequest const & cmd,
835                 FuncStatus & flag) const
836 {
837         // the font related toggles
838         //string tc = "mathnormal";
839         bool ret = true;
840         switch (cmd.action) {
841 #if 0
842         case LFUN_TABULAR_FEATURE:
843                 // FIXME: check temporarily disabled
844                 // valign code
845                 char align = mathcursor::valign();
846                 if (align == '\0') {
847                         enable = false;
848                         break;
849                 }
850                 if (cmd.argument.empty()) {
851                         flag.clear();
852                         break;
853                 }
854                 if (!contains("tcb", cmd.argument[0])) {
855                         enable = false;
856                         break;
857                 }
858                 flag.setOnOff(cmd.argument[0] == align);
859                 break;
860         case LFUN_BOLD:
861                 flag.setOnOff(tc == "mathbf");
862                 break;
863         case LFUN_SANS:
864                 flag.setOnOff(tc == "mathsf");
865                 break;
866         case LFUN_EMPH:
867                 flag.setOnOff(tc == "mathcal");
868                 break;
869         case LFUN_ROMAN:
870                 flag.setOnOff(tc == "mathrm");
871                 break;
872         case LFUN_CODE:
873                 flag.setOnOff(tc == "mathtt");
874                 break;
875         case LFUN_NOUN:
876                 flag.setOnOff(tc == "mathbb");
877                 break;
878         case LFUN_DEFAULT:
879                 flag.setOnOff(tc == "mathnormal");
880                 break;
881 #endif
882         case LFUN_MATH_MUTATE:
883                 //flag.setOnOff(mathcursor::formula()->hullType() == cmd.argument);
884                 flag.setOnOff(false);
885                 break;
886
887         // we just need to be in math mode to enable that
888         case LFUN_MATH_SIZE:
889         case LFUN_MATH_SPACE:
890         case LFUN_MATH_LIMITS:
891         case LFUN_MATH_NONUMBER:
892         case LFUN_MATH_NUMBER:
893         case LFUN_MATH_EXTERN:
894                 flag.enabled(true);
895                 break;
896
897         default:
898                 ret = false;
899                 break;
900         }
901         return ret;
902 }
903
904
905 void MathNestInset::edit(LCursor & cur, bool left)
906 {
907         cur.push(*this);
908         cur.idx() = left ? 0 : cur.lastidx();
909         cur.pos() = left ? 0 : cur.lastpos();
910         cur.resetAnchor();
911         lyxerr << "MathNestInset::edit, cur:\n" << cur << endl;
912 }
913
914
915 InsetBase * MathNestInset::editXY(LCursor & cur, int x, int y) const
916 {
917         int idx_min = 0;
918         int dist_min = 1000000;
919         for (idx_type i = 0; i < nargs(); ++i) {
920                 int d = cell(i).dist(x, y);
921                 if (d < dist_min) {
922                         dist_min = d;
923                         idx_min = i;
924                 }
925         }
926         MathArray const & ar = cell(idx_min);
927         cur.push(const_cast<MathNestInset&>(*this));
928         cur.idx() = idx_min;
929         cur.pos() = ar.x2pos(x - ar.xo());
930         lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
931         if (dist_min == 0) {
932                 // hit inside cell
933                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
934                         if (ar[i]->covers(x, y))
935                                 return ar[i].nucleus()->editXY(cur, x, y);
936         }
937         return const_cast<MathNestInset*>(this);
938 }
939
940
941 void MathNestInset::lfunMousePress(LCursor & cur, FuncRequest & cmd)
942 {
943         lyxerr << "lfunMousePress: buttons: " << cmd.button() << endl;
944         if (cmd.button() == mouse_button::button1) {
945                 first_x = cmd.x;
946                 first_y = cmd.y;
947                 lyxerr << "lfunMousePress: setting cursor to: " << cur << endl;
948                 cur.resetAnchor();
949                 cur.bv().cursor() = cur;
950         }
951
952         if (cmd.button() == mouse_button::button2) {
953                 cur.dispatch(FuncRequest(LFUN_PASTESELECTION));
954         }
955 }
956
957
958 void MathNestInset::lfunMouseMotion(LCursor & cur, FuncRequest & cmd)
959 {
960         // only select with button 1
961         if (cmd.button() == mouse_button::button1) {
962                 LCursor & bvcur = cur.bv().cursor();
963                 if (abs(cmd.x - first_x) + abs(cmd.y - first_y) > 4
964                     && bvcur.anchor_.hasPart(cur)) {
965                         first_x = cmd.x;
966                         first_y = cmd.y;
967
968                         bvcur.setCursor(cur);
969                         bvcur.selection() = true;
970                 } else
971                         cur.undispatched();
972         }
973 }
974
975
976 void MathNestInset::lfunMouseRelease(LCursor & cur, FuncRequest & cmd)
977 {
978         lyxerr << "lfunMouseRelease: buttons: " << cmd.button() << endl;
979
980         if (cmd.button() == mouse_button::button1) {
981                 //cur.bv().stuffClipboard(cur.grabSelection());
982                 return;
983         }
984
985         if (cmd.button() == mouse_button::button2) {
986                 MathArray ar;
987                 asArray(cur.bv().getClipboard(), ar);
988                 cur.clearSelection();
989                 cur.setScreenPos(cmd.x, cmd.y);
990                 cur.insert(ar);
991                 cur.bv().update();
992                 return;
993         }
994
995         if (cmd.button() == mouse_button::button3) {
996                 // try to dispatch to enclosed insets first
997                 cur.bv().owner()->getDialogs().show("mathpanel");
998                 return;
999         }
1000
1001         cur.undispatched();
1002 }
1003
1004
1005 bool MathNestInset::interpret(LCursor & cur, char c)
1006 {
1007         lyxerr << "interpret 2: '" << c << "'" << endl;
1008         cur.clearTargetX();
1009
1010         // handle macroMode
1011         if (cur.inMacroMode()) {
1012                 string name = cur.macroName();
1013
1014                 /// are we currently typing '#1' or '#2' or...?
1015                 if (name == "\\#") {
1016                         cur.backspace();
1017                         int n = c - '0';
1018                         if (n >= 1 && n <= 9)
1019                                 cur.insert(new MathMacroArgument(n));
1020                         return true;
1021                 }
1022
1023                 if (isalpha(c)) {
1024                         cur.activeMacro()->setName(name + c);
1025                         return true;
1026                 }
1027
1028                 // handle 'special char' macros
1029                 if (name == "\\") {
1030                         // remove the '\\'
1031                         if (c == '\\') {
1032                                 cur.backspace();
1033                                 if (currentMode() == MathInset::TEXT_MODE)
1034                                         cur.niceInsert(createMathInset("textbackslash"));
1035                                 else
1036                                         cur.niceInsert(createMathInset("backslash"));
1037                         } else if (c == '{') {
1038                                 cur.backspace();
1039                                 cur.niceInsert(MathAtom(new MathBraceInset));
1040                         } else if (c == '%') {
1041                                 cur.backspace();
1042                                 cur.niceInsert(MathAtom(new MathCommentInset));
1043                         } else if (c == '#') {
1044                                 BOOST_ASSERT(cur.activeMacro());
1045                                 cur.activeMacro()->setName(name + c);
1046                         } else {
1047                                 cur.backspace();
1048                                 cur.niceInsert(createMathInset(string(1, c)));
1049                         }
1050                         return true;
1051                 }
1052
1053                 // leave macro mode and try again if necessary
1054                 cur.macroModeClose();
1055                 if (c == '{')
1056                         cur.niceInsert(MathAtom(new MathBraceInset));
1057                 else if (c != ' ')
1058                         interpret(cur, c);
1059                 return true;
1060         }
1061
1062         // This is annoying as one has to press <space> far too often.
1063         // Disable it.
1064
1065 #if 0
1066                 // leave autocorrect mode if necessary
1067                 if (autocorrect() && c == ' ') {
1068                         autocorrect() = false;
1069                         return true;
1070                 }
1071 #endif
1072
1073         // just clear selection on pressing the space bar
1074         if (cur.selection() && c == ' ') {
1075                 cur.selection() = false;
1076                 return true;
1077         }
1078
1079         selClearOrDel(cur);
1080
1081         if (c == '\\') {
1082                 //lyxerr << "starting with macro" << endl;
1083                 cur.insert(MathAtom(new MathUnknownInset("\\", false)));
1084                 return true;
1085         }
1086
1087         if (c == '\n') {
1088                 if (currentMode() == MathInset::TEXT_MODE)
1089                         cur.insert(c);
1090                 return true;
1091         }
1092
1093         if (c == ' ') {
1094                 if (currentMode() == MathInset::TEXT_MODE) {
1095                         // insert spaces in text mode,
1096                         // but suppress direct insertion of two spaces in a row
1097                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1098                         // it is better than nothing...
1099                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ')
1100                                 cur.insert(c);
1101                         return true;
1102                 }
1103                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1104                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1105                         return true;
1106                 }
1107                 if (cur.popRight())
1108                         return true;
1109                 // if are at the very end, leave the formula
1110                 return cur.pos() != cur.lastpos();
1111         }
1112
1113         if (c == '_') {
1114                 script(cur, false);
1115                 return true;
1116         }
1117
1118         if (c == '^') {
1119                 script(cur, true);
1120                 return true;
1121         }
1122
1123         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' || c == '%') {
1124                 cur.niceInsert(createMathInset(string(1, c)));
1125                 return true;
1126         }
1127
1128         if (c == '~') {
1129                 cur.niceInsert(createMathInset("sim"));
1130                 return true;
1131         }
1132
1133         // try auto-correction
1134         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1135         //      return true;
1136
1137         // no special circumstances, so insert the character without any fuss
1138         cur.insert(c);
1139         cur.autocorrect() = true;
1140         return true;
1141 }
1142
1143
1144 bool MathNestInset::script(LCursor & cur, bool up)
1145 {
1146         // Hack to get \^ and \_ working
1147         lyxerr << "handling script: up: " << up << endl;
1148         if (cur.inMacroMode() && cur.macroName() == "\\") {
1149                 if (up)
1150                         cur.niceInsert(createMathInset("mathcircumflex"));
1151                 else
1152                         interpret(cur, '_');
1153                 return true;
1154         }
1155
1156         cur.macroModeClose();
1157         string safe = grabAndEraseSelection(cur);
1158         if (asScriptInset() && cur.idx() == 0) {
1159                 // we are in a nucleus of a script inset, move to _our_ script
1160                 MathScriptInset * inset = asScriptInset();
1161                 lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1162                 inset->ensure(up);
1163                 cur.idx() = inset->idxOfScript(up);
1164                 cur.pos() = 0;
1165         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1166                 --cur.pos();
1167                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1168                 cur.push(*inset);
1169                 cur.idx() = inset->idxOfScript(up);
1170                 cur.pos() = cur.lastpos();
1171         } else {
1172                 // convert the thing to our left to a scriptinset or create a new
1173                 // one if in the very first position of the array
1174                 if (cur.pos() == 0) {
1175                         lyxerr << "new scriptinset" << endl;
1176                         cur.insert(new MathScriptInset(up));
1177                 } else {
1178                         lyxerr << "converting prev atom " << endl;
1179                         cur.prevAtom() = MathAtom(new MathScriptInset(cur.prevAtom(), up));
1180                 }
1181                 --cur.pos();
1182                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1183                 cur.push(*inset);
1184                 cur.idx() = 1;
1185                 cur.pos() = 0;
1186         }
1187         lyxerr << "pasting 1: safe:\n" << safe << endl;
1188         cur.paste(safe);
1189         cur.resetAnchor();
1190         lyxerr << "pasting 2: safe:\n" << safe << endl;
1191         return true;
1192 }