]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathNest.C
a882e0e65949b7ee1af61b0a62081ba7601ba8e9
[features.git] / src / mathed / InsetMathNest.C
1 /**
2  * \file InsetMathNest.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 "InsetMathNest.h"
14
15 #include "InsetMathArray.h"
16 #include "InsetMathBig.h"
17 #include "InsetMathBox.h"
18 #include "InsetMathBrace.h"
19 #include "InsetMathColor.h"
20 #include "InsetMathComment.h"
21 #include "MathData.h"
22 #include "InsetMathDelim.h"
23 #include "MathFactory.h"
24 #include "InsetMathHull.h"
25 #include "MathMLStream.h"
26 #include "MathMacroArgument.h"
27 //#include "InsetMathMBox.h"
28 #include "MathParser.h"
29 #include "InsetMathScript.h"
30 #include "InsetMathSpace.h"
31 #include "InsetMathSymbol.h"
32 #include "MathSupport.h"
33 #include "InsetMathUnknown.h"
34 #include "InsetMathRef.h"
35
36 #include "BufferView.h"
37 #include "CutAndPaste.h"
38 #include "FuncStatus.h"
39 #include "LColor.h"
40 #include "bufferview_funcs.h"
41 #include "coordcache.h"
42 #include "cursor.h"
43 #include "debug.h"
44 #include "dispatchresult.h"
45 #include "funcrequest.h"
46 #include "gettext.h"
47 #include "outputparams.h"
48 #include "undo.h"
49
50 #include "support/lstrings.h"
51
52 #include "frontends/Painter.h"
53 #include "frontends/Selection.h"
54 #include "frontends/nullpainter.h"
55
56 #include "funcrequest.h"
57 #include "lyxserver.h"
58 #include "lyxsocket.h"
59
60 #include <sstream>
61
62 using lyx::docstring;
63 using lyx::cap::copySelection;
64 using lyx::cap::grabAndEraseSelection;
65 using lyx::cap::cutSelection;
66 using lyx::cap::replaceSelection;
67 using lyx::cap::selClearOrDel;
68
69 using std::endl;
70 using std::string;
71 using std::istringstream;
72
73
74 InsetMathNest::InsetMathNest(idx_type nargs)
75         : cells_(nargs), lock_(false)
76 {}
77
78
79 InsetMath::idx_type InsetMathNest::nargs() const
80 {
81         return cells_.size();
82 }
83
84
85 MathArray & InsetMathNest::cell(idx_type i)
86 {
87         return cells_[i];
88 }
89
90
91 MathArray const & InsetMathNest::cell(idx_type i) const
92 {
93         return cells_[i];
94 }
95
96
97 void InsetMathNest::cursorPos(CursorSlice const & sl, bool /*boundary*/,
98         int & x, int & y) const
99 {
100 // FIXME: This is a hack. Ideally, the coord cache should not store
101 // absolute positions, but relative ones. This would mean to call
102 // setXY() not in MathArray::draw(), but in the parent insets' draw()
103 // with the correctly adjusted x,y values. But this means that we'd have
104 // to touch all (math)inset's draw() methods. Right now, we'll store
105 // absolute value, and make them here relative, only to make them
106 // absolute again when actually drawing the cursor. What a mess.
107         BOOST_ASSERT(ptr_cmp(&sl.inset(), this));
108         MathArray const & ar = sl.cell();
109         if (!theCoords.getArrays().has(&ar)) {
110                 // this can (semi-)legally happen if we just created this cell
111                 // and it never has been drawn before. So don't ASSERT.
112                 //lyxerr << "no cached data for array " << &ar << endl;
113                 x = 0;
114                 y = 0;
115                 return;
116         }
117         Point const pt = theCoords.getArrays().xy(&ar);
118         if (!theCoords.getInsets().has(this)) {
119                 // same as above
120                 //lyxerr << "no cached data for inset " << this << endl;
121                 x = 0;
122                 y = 0;
123                 return;
124         }
125         Point const pt2 = theCoords.getInsets().xy(this);
126         //lyxerr << "retrieving position cache for MathArray "
127         //      << pt.x_ << ' ' << pt.y_ << std::endl;
128         x = pt.x_ - pt2.x_ + ar.pos2x(sl.pos());
129         y = pt.y_ - pt2.y_;
130 //      lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
131 //              << " asc: " << ascent() << "  des: " << descent()
132 //              << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
133         // move cursor visually into empty cells ("blue rectangles");
134         if (ar.empty())
135                 x += 2;
136 }
137
138
139 void InsetMathNest::metrics(MetricsInfo const & mi) const
140 {
141         MetricsInfo m = mi;
142         for (idx_type i = 0, n = nargs(); i != n; ++i)
143                 cell(i).metrics(m);
144 }
145
146
147 bool InsetMathNest::idxNext(LCursor & cur) const
148 {
149         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
150         if (cur.idx() == cur.lastidx())
151                 return false;
152         ++cur.idx();
153         cur.pos() = 0;
154         return true;
155 }
156
157
158 bool InsetMathNest::idxRight(LCursor & cur) const
159 {
160         return idxNext(cur);
161 }
162
163
164 bool InsetMathNest::idxPrev(LCursor & cur) const
165 {
166         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
167         if (cur.idx() == 0)
168                 return false;
169         --cur.idx();
170         cur.pos() = cur.lastpos();
171         return true;
172 }
173
174
175 bool InsetMathNest::idxLeft(LCursor & cur) const
176 {
177         return idxPrev(cur);
178 }
179
180
181 bool InsetMathNest::idxFirst(LCursor & cur) const
182 {
183         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
184         if (nargs() == 0)
185                 return false;
186         cur.idx() = 0;
187         cur.pos() = 0;
188         return true;
189 }
190
191
192 bool InsetMathNest::idxLast(LCursor & cur) const
193 {
194         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
195         if (nargs() == 0)
196                 return false;
197         cur.idx() = cur.lastidx();
198         cur.pos() = cur.lastpos();
199         return true;
200 }
201
202
203 void InsetMathNest::dump() const
204 {
205         WriteStream os(lyxerr);
206         os << "---------------------------------------------\n";
207         write(os);
208         os << "\n";
209         for (idx_type i = 0, n = nargs(); i != n; ++i)
210                 os << cell(i) << "\n";
211         os << "---------------------------------------------\n";
212 }
213
214
215 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
216 {
217 #if 0
218         if (lock_)
219                 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
220                                         LColor::mathlockbg);
221 #endif
222         setPosCache(pi, x, y);
223 }
224
225
226 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
227 {
228         // this should use the x/y values given, not the cached values
229         LCursor & cur = pi.base.bv->cursor();
230         if (!cur.selection())
231                 return;
232         if (!ptr_cmp(&cur.inset(), this))
233                 return;
234
235         // FIXME: hack to get position cache warm
236         static lyx::frontend::NullPainter nop;
237         PainterInfo pinop(pi);
238         pinop.pain = nop;
239         draw(pinop, x, y);
240
241         CursorSlice s1 = cur.selBegin();
242         CursorSlice s2 = cur.selEnd();
243         //lyxerr << "InsetMathNest::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 << "InsetMathNest::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 InsetMathNest::validate(LaTeXFeatures & features) const
271 {
272         for (idx_type i = 0; i < nargs(); ++i)
273                 cell(i).validate(features);
274 }
275
276
277 void InsetMathNest::replace(ReplaceData & rep)
278 {
279         for (idx_type i = 0; i < nargs(); ++i)
280                 cell(i).replace(rep);
281 }
282
283
284 bool InsetMathNest::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 InsetMathNest::lock() const
294 {
295         return lock_;
296 }
297
298
299 void InsetMathNest::lock(bool l)
300 {
301         lock_ = l;
302 }
303
304
305 bool InsetMathNest::isActive() const
306 {
307         return nargs() > 0;
308 }
309
310
311 MathArray InsetMathNest::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 InsetMathNest::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 InsetMathNest::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 InsetMathNest::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 bool InsetMathNest::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                 InsetMathScript * 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                 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
373                 InsetMathFont 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         return false;
382 }
383
384
385 void InsetMathNest::handleFont
386         (LCursor & cur, string const & arg, string const & font)
387 {
388         // this whole function is a hack and won't work for incremental font
389         // changes...
390         recordUndo(cur, Undo::ATOMIC);
391
392         if (cur.inset().asInsetMath()->name() == font)
393                 cur.handleFont(font);
394         else {
395                 cur.handleNest(createInsetMath(font));
396                 cur.insert(arg);
397         }
398 }
399
400
401 void InsetMathNest::handleFont2(LCursor & cur, string const & arg)
402 {
403         recordUndo(cur, Undo::ATOMIC);
404         LyXFont font;
405         bool b;
406         bv_funcs::string2font(arg, font, b);
407         if (font.color() != LColor::inherit) {
408                 MathAtom at = MathAtom(new InsetMathColor(true, font.color()));
409                 cur.handleNest(at, 0);
410         }
411 }
412
413
414 void InsetMathNest::doDispatch(LCursor & cur, FuncRequest & cmd)
415 {
416         //lyxerr << "InsetMathNest: 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(lyx::to_utf8(cmd.argument()));
427                 is >> n;
428                 docstring const selection = lyx::cap::getSelection(cur.buffer(), n);
429                 // FIXME UNICODE
430                 cur.niceInsert(lyx::to_utf8(selection));
431                 cur.clearSelection(); // bug 393
432                 cur.bv().switchKeyMap();
433                 finishUndo();
434                 break;
435         }
436
437         case LFUN_CUT:
438                 recordUndo(cur);
439                 cutSelection(cur, true, true);
440                 cur.message(_("Cut"));
441                 // Prevent stale position >= size crash
442                 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
443                 cur.normalize();
444                 break;
445
446         case LFUN_COPY:
447                 copySelection(cur);
448                 // FIXME UNICODE
449                 cur.message(_("Copy"));
450                 break;
451
452         case LFUN_MOUSE_PRESS:
453                 lfunMousePress(cur, cmd);
454                 break;
455
456         case LFUN_MOUSE_MOTION:
457                 lfunMouseMotion(cur, cmd);
458                 break;
459
460         case LFUN_MOUSE_RELEASE:
461                 lfunMouseRelease(cur, cmd);
462                 break;
463
464         case LFUN_FINISHED_LEFT:
465                 cur.bv().cursor() = cur;
466                 break;
467
468         case LFUN_FINISHED_RIGHT:
469                 ++cur.pos();
470                 cur.bv().cursor() = cur;
471                 break;
472
473         case LFUN_FINISHED_UP:
474                 cur.bv().cursor() = cur;
475                 break;
476
477         case LFUN_FINISHED_DOWN:
478                 ++cur.pos();
479                 cur.bv().cursor() = cur;
480                 break;
481
482         case LFUN_CHAR_FORWARD_SELECT:
483         case LFUN_CHAR_FORWARD:
484                 cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
485                 cur.autocorrect() = false;
486                 cur.clearTargetX();
487                 cur.macroModeClose();
488                 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
489                         cur.pushLeft(*cur.nextAtom().nucleus());
490                         cur.inset().idxFirst(cur);
491                 } else if (cur.posRight() || idxRight(cur)
492                         || cur.popRight() || cur.selection())
493                         ;
494                 else {
495                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
496                         cur.undispatched();
497                 }
498                 break;
499
500         case LFUN_CHAR_BACKWARD_SELECT:
501         case LFUN_CHAR_BACKWARD:
502                 cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
503                 cur.autocorrect() = false;
504                 cur.clearTargetX();
505                 cur.macroModeClose();
506                 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
507                         cur.posLeft();
508                         cur.push(*cur.nextAtom().nucleus());
509                         cur.inset().idxLast(cur);
510                 } else if (cur.posLeft() || idxLeft(cur)
511                         || cur.popLeft() || cur.selection())
512                         ;
513                 else {
514                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
515                         cur.undispatched();
516                 }
517                 break;
518
519         case LFUN_UP_SELECT:
520         case LFUN_UP:
521                 // FIXME Tried to use clearTargetX and macroModeClose, crashed on cur.up()
522                 if (cur.inMacroMode()) {
523                         // Make Helge happy
524                         cur.macroModeClose();
525                         break;
526                 }
527                 cur.selHandle(cmd.action == LFUN_UP_SELECT);
528                 if (!cur.up()) {
529                         cmd = FuncRequest(LFUN_FINISHED_UP);
530                         cur.undispatched();
531                 }
532                 // fixes bug 1598. Please check!
533                 cur.normalize();
534                 break;
535
536         case LFUN_DOWN_SELECT:
537         case LFUN_DOWN:
538                 if (cur.inMacroMode()) {
539                         cur.macroModeClose();
540                         break;
541                 }
542                 cur.selHandle(cmd.action == LFUN_DOWN_SELECT);
543                 if (!cur.down()) {
544                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
545                         cur.undispatched();
546                 }
547                 // fixes bug 1598. Please check!
548                 cur.normalize();
549                 break;
550
551         case LFUN_MOUSE_DOUBLE:
552         case LFUN_MOUSE_TRIPLE:
553         case LFUN_WORD_SELECT:
554                 cur.pos() = 0;
555                 cur.idx() = 0;
556                 cur.resetAnchor();
557                 cur.selection() = true;
558                 cur.pos() = cur.lastpos();
559                 cur.idx() = cur.lastidx();
560                 break;
561
562         case LFUN_PARAGRAPH_UP_SELECT:
563         case LFUN_PARAGRAPH_UP:
564         case LFUN_PARAGRAPH_DOWN_SELECT:
565         case LFUN_PARAGRAPH_DOWN:
566                 break;
567
568         case LFUN_LINE_BEGIN_SELECT:
569         case LFUN_LINE_BEGIN:
570         case LFUN_WORD_BACKWARD_SELECT:
571         case LFUN_WORD_BACKWARD:
572                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
573                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
574                 cur.macroModeClose();
575                 if (cur.pos() != 0) {
576                         cur.pos() = 0;
577                 } else if (cur.col() != 0) {
578                         cur.idx() -= cur.col();
579                         cur.pos() = 0;
580                 } else if (cur.idx() != 0) {
581                         cur.idx() = 0;
582                         cur.pos() = 0;
583                 } else {
584                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
585                         cur.undispatched();
586                 }
587                 break;
588
589         case LFUN_WORD_FORWARD_SELECT:
590         case LFUN_WORD_FORWARD:
591         case LFUN_LINE_END_SELECT:
592         case LFUN_LINE_END:
593                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
594                                 cmd.action == LFUN_LINE_END_SELECT);
595                 cur.macroModeClose();
596                 cur.clearTargetX();
597                 if (cur.pos() != cur.lastpos()) {
598                         cur.pos() = cur.lastpos();
599                 } else if (ncols() && (cur.col() != cur.lastcol())) {
600                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
601                         cur.pos() = cur.lastpos();
602                 } else if (cur.idx() != cur.lastidx()) {
603                         cur.idx() = cur.lastidx();
604                         cur.pos() = cur.lastpos();
605                 } else {
606                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
607                         cur.undispatched();
608                 }
609                 break;
610
611         case LFUN_SCREEN_UP_SELECT:
612         case LFUN_SCREEN_UP:
613                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
614                 cur.undispatched();
615                 break;
616
617         case LFUN_SCREEN_DOWN_SELECT:
618         case LFUN_SCREEN_DOWN:
619                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
620                 cur.undispatched();
621                 break;
622
623         case LFUN_CELL_FORWARD:
624                 cur.inset().idxNext(cur);
625                 break;
626
627         case LFUN_CELL_BACKWARD:
628                 cur.inset().idxPrev(cur);
629                 break;
630
631         case LFUN_WORD_DELETE_BACKWARD:
632         case LFUN_CHAR_DELETE_BACKWARD:
633                 if (cur.pos() == 0)
634                         // May affect external cell:
635                         recordUndoInset(cur, Undo::ATOMIC);
636                 else
637                         recordUndo(cur, Undo::ATOMIC);
638                 cur.backspace();
639                 break;
640
641         case LFUN_WORD_DELETE_FORWARD:
642         case LFUN_CHAR_DELETE_FORWARD:
643                 if (cur.pos() == cur.lastpos())
644                         // May affect external cell:
645                         recordUndoInset(cur, Undo::ATOMIC);
646                 else
647                         recordUndo(cur, Undo::ATOMIC);
648                 cur.erase();
649                 break;
650
651         case LFUN_ESCAPE:
652                 if (cur.selection())
653                         cur.clearSelection();
654                 else  {
655                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
656                         cur.undispatched();
657                 }
658                 break;
659
660         case LFUN_INSET_TOGGLE:
661                 recordUndo(cur);
662                 lock(!lock());
663                 cur.popRight();
664                 break;
665
666         case LFUN_SELF_INSERT:
667                 if (cmd.argument().size() != 1) {
668                         recordUndo(cur);
669                         string const arg = lyx::to_utf8(cmd.argument());
670                         if (!interpret(cur, arg))
671                                 cur.insert(arg);
672                         break;
673                 }
674                 // Don't record undo steps if we are in macro mode and
675                 // cmd.argument is the next character of the macro name.
676                 // Otherwise we'll get an invalid cursor if we undo after
677                 // the macro was finished and the macro is a known command,
678                 // e.g. sqrt. LCursor::macroModeClose replaces in this case
679                 // the InsetMathUnknown with name "frac" by an empty
680                 // InsetMathFrac -> a pos value > 0 is invalid.
681                 // A side effect is that an undo before the macro is finished
682                 // undoes the complete macro, not only the last character.
683                 if (!cur.inMacroMode())
684                         recordUndo(cur);
685
686                 // spacial handling of space. If we insert an inset
687                 // via macro mode, we want to put the cursor inside it
688                 // if relevant. Think typing "\frac<space>".
689                 if (cmd.argument()[0] == ' '
690                     && cur.inMacroMode() && cur.macroName() != "\\"
691                     && cur.macroModeClose()) {
692                         MathAtom const atom = cur.prevAtom();
693                         if (atom->asNestInset() && atom->nargs() > 0) {
694                                 cur.posLeft();
695                                 cur.pushLeft(*cur.nextInset());
696                         }
697                 // FIXME: Change to
698                 // } else if (!interpret(cur, cmd.argument()[0])) {
699                 // when interpret accepts UCS4 characters
700                 } else if (!interpret(cur, lyx::to_utf8(cmd.argument()))) {
701                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
702                         cur.undispatched();
703                 }
704                 break;
705
706         //case LFUN_SERVER_GET_XY:
707         //      sprintf(dispatch_buffer, "%d %d",);
708         //      break;
709
710         case LFUN_SERVER_SET_XY: {
711                 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
712                 int x = 0;
713                 int y = 0;
714                 istringstream is(lyx::to_utf8(cmd.argument()));
715                 is >> x >> y;
716                 cur.setScreenPos(x, y);
717                 break;
718         }
719
720         // Special casing for superscript in case of LyX handling
721         // dead-keys:
722         case LFUN_ACCENT_CIRCUMFLEX:
723                 if (cmd.argument().empty()) {
724                         // do superscript if LyX handles
725                         // deadkeys
726                         recordUndo(cur, Undo::ATOMIC);
727                         script(cur, true, grabAndEraseSelection(cur));
728                 }
729                 break;
730
731         case LFUN_ACCENT_UMLAUT:
732         case LFUN_ACCENT_ACUTE:
733         case LFUN_ACCENT_GRAVE:
734         case LFUN_ACCENT_BREVE:
735         case LFUN_ACCENT_DOT:
736         case LFUN_ACCENT_MACRON:
737         case LFUN_ACCENT_CARON:
738         case LFUN_ACCENT_TILDE:
739         case LFUN_ACCENT_CEDILLA:
740         case LFUN_ACCENT_CIRCLE:
741         case LFUN_ACCENT_UNDERDOT:
742         case LFUN_ACCENT_TIE:
743         case LFUN_ACCENT_OGONEK:
744         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
745                 break;
746
747         //  Math fonts
748         case LFUN_FONT_FREE_APPLY:
749         case LFUN_FONT_FREE_UPDATE:
750                 handleFont2(cur, lyx::to_utf8(cmd.argument()));
751                 break;
752
753         case LFUN_FONT_BOLD:
754                 if (currentMode() == TEXT_MODE)
755                         handleFont(cur, lyx::to_utf8(cmd.argument()), "textbf");
756                 else
757                         handleFont(cur, lyx::to_utf8(cmd.argument()), "mathbf");
758                 break;
759         case LFUN_FONT_SANS:
760                 if (currentMode() == TEXT_MODE)
761                         handleFont(cur, lyx::to_utf8(cmd.argument()), "textsf");
762                 else
763                         handleFont(cur, lyx::to_utf8(cmd.argument()), "mathsf");
764                 break;
765         case LFUN_FONT_EMPH:
766                 if (currentMode() == TEXT_MODE)
767                         handleFont(cur, lyx::to_utf8(cmd.argument()), "emph");
768                 else
769                         handleFont(cur, lyx::to_utf8(cmd.argument()), "mathcal");
770                 break;
771         case LFUN_FONT_ROMAN:
772                 if (currentMode() == TEXT_MODE)
773                         handleFont(cur, lyx::to_utf8(cmd.argument()), "textrm");
774                 else
775                         handleFont(cur, lyx::to_utf8(cmd.argument()), "mathrm");
776                 break;
777         case LFUN_FONT_CODE:
778                 if (currentMode() == TEXT_MODE)
779                         handleFont(cur, lyx::to_utf8(cmd.argument()), "texttt");
780                 else
781                         handleFont(cur, lyx::to_utf8(cmd.argument()), "mathtt");
782                 break;
783         case LFUN_FONT_FRAK:
784                 handleFont(cur, lyx::to_utf8(cmd.argument()), "mathfrak");
785                 break;
786         case LFUN_FONT_ITAL:
787                 if (currentMode() == TEXT_MODE)
788                         handleFont(cur, lyx::to_utf8(cmd.argument()), "textit");
789                 else
790                         handleFont(cur, lyx::to_utf8(cmd.argument()), "mathit");
791                 break;
792         case LFUN_FONT_NOUN:
793                 if (currentMode() == TEXT_MODE)
794                         // FIXME: should be "noun"
795                         handleFont(cur, lyx::to_utf8(cmd.argument()), "textsc");
796                 else
797                         handleFont(cur, lyx::to_utf8(cmd.argument()), "mathbb");
798                 break;
799         //case LFUN_FONT_FREE_APPLY:
800                 handleFont(cur, lyx::to_utf8(cmd.argument()), "textrm");
801                 break;
802         case LFUN_FONT_DEFAULT:
803                 handleFont(cur, lyx::to_utf8(cmd.argument()), "textnormal");
804                 break;
805
806         case LFUN_MATH_MODE: {
807 #if 1
808                 // ignore math-mode on when already in math mode
809                 if (currentMode() == InsetBase::MATH_MODE && cmd.argument() == "on")
810                         break;
811                 cur.macroModeClose();
812                 string const save_selection = grabAndEraseSelection(cur);
813                 selClearOrDel(cur);
814                 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
815                 cur.plainInsert(MathAtom(new InsetMathBox("mbox")));
816                 cur.posLeft();
817                 cur.pushLeft(*cur.nextInset());
818                 cur.niceInsert(save_selection);
819 #else
820                 if (currentMode() == InsetBase::TEXT_MODE) {
821                         cur.niceInsert(MathAtom(new InsetMathHull("simple")));
822                         cur.message(_("create new math text environment ($...$)"));
823                 } else {
824                         handleFont(cur, lyx::to_utf8(cmd.argument()), "textrm");
825                         cur.message(_("entered math text mode (textrm)"));
826                 }
827 #endif
828                 break;
829         }
830
831         case LFUN_MATH_SIZE:
832 #if 0
833                 recordUndo(cur);
834                 cur.setSize(arg);
835 #endif
836                 break;
837
838         case LFUN_MATH_MATRIX: {
839                 recordUndo(cur, Undo::ATOMIC);
840                 unsigned int m = 1;
841                 unsigned int n = 1;
842                 string v_align;
843                 string h_align;
844                 istringstream is(lyx::to_utf8(cmd.argument()));
845                 is >> m >> n >> v_align >> h_align;
846                 if (m < 1)
847                         m = 1;
848                 if (n < 1)
849                         n = 1;
850                 v_align += 'c';
851                 cur.niceInsert(
852                         MathAtom(new InsetMathArray("array", m, n, v_align[0], h_align)));
853                 break;
854         }
855
856         case LFUN_MATH_DELIM: {
857                 string ls;
858                 string rs = lyx::support::split(lyx::to_utf8(cmd.argument()), ls, ' ');
859                 // Reasonable default values
860                 if (ls.empty())
861                         ls = '(';
862                 if (rs.empty())
863                         rs = ')';
864                 recordUndo(cur, Undo::ATOMIC);
865                 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
866                 break;
867         }
868
869         case LFUN_MATH_BIGDELIM: {
870                 string const lname = cmd.getArg(0);
871                 string const ldelim = cmd.getArg(1);
872                 string const rname = cmd.getArg(2);
873                 string const rdelim = cmd.getArg(3);
874                 latexkeys const * l = in_word_set(lname);
875                 bool const have_l = l && l->inset == "big" &&
876                                     InsetMathBig::isBigInsetDelim(ldelim);
877                 l = in_word_set(rname);
878                 bool const have_r = l && l->inset == "big" &&
879                                     InsetMathBig::isBigInsetDelim(rdelim);
880                 // We mimic LFUN_MATH_DELIM in case we have an empty left
881                 // or right delimiter.
882                 if (have_l || have_r) {
883                         recordUndo(cur, Undo::ATOMIC);
884                         string const selection = grabAndEraseSelection(cur);
885                         selClearOrDel(cur);
886                         if (have_l)
887                                 cur.insert(MathAtom(new InsetMathBig(lname,
888                                                                 ldelim)));
889                         cur.niceInsert(selection);
890                         if (have_r)
891                                 cur.insert(MathAtom(new InsetMathBig(rname,
892                                                                 rdelim)));
893                 }
894                 // Don't call cur.undispatched() if we did nothing, this would
895                 // lead to infinite recursion via LyXText::dispatch().
896                 break;
897         }
898
899         case LFUN_SPACE_INSERT:
900         case LFUN_MATH_SPACE:
901                 recordUndo(cur, Undo::ATOMIC);
902                 cur.insert(MathAtom(new InsetMathSpace(",")));
903                 break;
904
905         case LFUN_ERT_INSERT:
906                 // interpret this as if a backslash was typed
907                 recordUndo(cur, Undo::ATOMIC);
908                 interpret(cur, '\\');
909                 break;
910
911         case LFUN_MATH_SUBSCRIPT:
912                 // interpret this as if a _ was typed
913                 recordUndo(cur, Undo::ATOMIC);
914                 interpret(cur, '_');
915                 break;
916
917         case LFUN_MATH_SUPERSCRIPT:
918                 // interpret this as if a ^ was typed
919                 recordUndo(cur, Undo::ATOMIC);
920                 interpret(cur, '^');
921                 break;
922
923 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
924 // handling such that "self-insert" works on "arbitrary stuff" too, and
925 // math-insert only handles special math things like "matrix".
926         case LFUN_MATH_INSERT: {
927                 recordUndo(cur, Undo::ATOMIC);
928                 if (cmd.argument() == "^" || cmd.argument() == "_")
929                         interpret(cur, cmd.argument()[0]);
930                 else
931                         cur.niceInsert(lyx::to_utf8(cmd.argument()));
932                 break;
933                 }
934
935         case LFUN_DIALOG_SHOW_NEW_INSET: {
936                 string const & name = lyx::to_utf8(cmd.argument());
937                 string data;
938                 if (name == "ref") {
939                         RefInset tmp(name);
940                         data = tmp.createDialogStr(name);
941                 }
942                 cur.bv().showInsetDialog(name, data, 0);
943                 break;
944         }
945
946         case LFUN_INSET_INSERT: {
947                 MathArray ar;
948                 if (createInsetMath_fromDialogStr(lyx::to_utf8(cmd.argument()), ar)) {
949                         recordUndo(cur);
950                         cur.insert(ar);
951                 } else
952                         cur.undispatched();
953                 break;
954         }
955
956         default:
957                 InsetMathDim::doDispatch(cur, cmd);
958                 break;
959         }
960 }
961
962
963 bool InsetMathNest::getStatus(LCursor & cur, FuncRequest const & cmd,
964                 FuncStatus & flag) const
965 {
966         // the font related toggles
967         //string tc = "mathnormal";
968         bool ret = true;
969         string const arg = lyx::to_utf8(cmd.argument());
970         switch (cmd.action) {
971         case LFUN_TABULAR_FEATURE:
972                 flag.enabled(false);
973                 break;
974 #if 0
975         case LFUN_TABULAR_FEATURE:
976                 // FIXME: check temporarily disabled
977                 // valign code
978                 char align = mathcursor::valign();
979                 if (align == '\0') {
980                         enable = false;
981                         break;
982                 }
983                 if (cmd.argument().empty()) {
984                         flag.clear();
985                         break;
986                 }
987                 if (!contains("tcb", cmd.argument()[0])) {
988                         enable = false;
989                         break;
990                 }
991                 flag.setOnOff(cmd.argument()[0] == align);
992                 break;
993 #endif
994         /// We have to handle them since 1.4 blocks all unhandled actions
995         case LFUN_FONT_ITAL:
996         case LFUN_FONT_BOLD:
997         case LFUN_FONT_SANS:
998         case LFUN_FONT_EMPH:
999         case LFUN_FONT_CODE:
1000         case LFUN_FONT_NOUN:
1001         case LFUN_FONT_ROMAN:
1002         case LFUN_FONT_DEFAULT:
1003                 flag.enabled(true);
1004                 break;
1005         case LFUN_MATH_MUTATE:
1006                 //flag.setOnOff(mathcursor::formula()->hullType() == lyx::to_utf8(cmd.argument()));
1007                 flag.setOnOff(false);
1008                 break;
1009
1010         // we just need to be in math mode to enable that
1011         case LFUN_MATH_SIZE:
1012         case LFUN_MATH_SPACE:
1013         case LFUN_MATH_LIMITS:
1014         case LFUN_MATH_NONUMBER:
1015         case LFUN_MATH_NUMBER:
1016         case LFUN_MATH_EXTERN:
1017                 flag.enabled(true);
1018                 break;
1019
1020         case LFUN_FONT_FRAK:
1021                 flag.enabled(currentMode() != TEXT_MODE);
1022                 break;
1023
1024         case LFUN_MATH_INSERT: {
1025                 bool const textarg =
1026                         arg == "\\textbf"   || arg == "\\textsf" ||
1027                         arg == "\\textrm"   || arg == "\\textmd" ||
1028                         arg == "\\textit"   || arg == "\\textsc" ||
1029                         arg == "\\textsl"   || arg == "\\textup" ||
1030                         arg == "\\texttt"   || arg == "\\textbb" ||
1031                         arg == "\\textnormal";
1032                 flag.enabled(currentMode() != TEXT_MODE || textarg);
1033                 break;
1034         }
1035
1036         case LFUN_MATH_MATRIX:
1037                 flag.enabled(currentMode() == MATH_MODE);
1038                 break;
1039
1040         case LFUN_INSET_INSERT: {
1041                 // Don't test createMathInset_fromDialogStr(), since
1042                 // getStatus is not called with a valid reference and the
1043                 // dialog would not be applyable.
1044                 string const name = cmd.getArg(0);
1045                 flag.enabled(name == "ref");
1046                 break;
1047         }
1048
1049         case LFUN_MATH_DELIM:
1050         case LFUN_MATH_BIGDELIM:
1051                 // Don't do this with multi-cell selections
1052                 flag.enabled(cur.selBegin().idx() == cur.selEnd().idx());
1053                 break;
1054
1055         default:
1056                 ret = false;
1057                 break;
1058         }
1059         return ret;
1060 }
1061
1062
1063 void InsetMathNest::edit(LCursor & cur, bool left)
1064 {
1065         cur.push(*this);
1066         cur.idx() = left ? 0 : cur.lastidx();
1067         cur.pos() = left ? 0 : cur.lastpos();
1068         cur.resetAnchor();
1069         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1070 }
1071
1072
1073 InsetBase * InsetMathNest::editXY(LCursor & cur, int x, int y)
1074 {
1075         int idx_min = 0;
1076         int dist_min = 1000000;
1077         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1078                 int const d = cell(i).dist(x, y);
1079                 if (d < dist_min) {
1080                         dist_min = d;
1081                         idx_min = i;
1082                 }
1083         }
1084         MathArray & ar = cell(idx_min);
1085         cur.push(*this);
1086         cur.idx() = idx_min;
1087         cur.pos() = ar.x2pos(x - ar.xo());
1088         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1089         if (dist_min == 0) {
1090                 // hit inside cell
1091                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1092                         if (ar[i]->covers(x, y))
1093                                 return ar[i].nucleus()->editXY(cur, x, y);
1094         }
1095         return this;
1096 }
1097
1098
1099 void InsetMathNest::lfunMousePress(LCursor & cur, FuncRequest & cmd)
1100 {
1101         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1102         BufferView & bv = cur.bv();
1103         if (cmd.button() == mouse_button::button1) {
1104                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1105                 bv.mouseSetCursor(cur);
1106         } else if (cmd.button() == mouse_button::button2) {
1107                 MathArray ar;
1108                 if (cur.selection())
1109                         asArray(lyx::to_utf8(bv.cursor().selectionAsString(false)), ar);
1110                 else
1111                         asArray(lyx::to_utf8(theSelection().get()), ar);
1112
1113                 cur.insert(ar);
1114                 bv.mouseSetCursor(cur);
1115         }
1116 }
1117
1118
1119 void InsetMathNest::lfunMouseMotion(LCursor & cur, FuncRequest & cmd)
1120 {
1121         // only select with button 1
1122         if (cmd.button() == mouse_button::button1) {
1123                 LCursor & bvcur = cur.bv().cursor();
1124                 if (bvcur.anchor_.hasPart(cur)) {
1125                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1126                         bvcur.setCursor(cur);
1127                         bvcur.selection() = true;
1128                         //lyxerr << "MOTION " << bvcur << endl;
1129                 }
1130                 else {
1131                         cur.undispatched();
1132                 }
1133         }
1134 }
1135
1136
1137 void InsetMathNest::lfunMouseRelease(LCursor & cur, FuncRequest & cmd)
1138 {
1139         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1140
1141         if (cmd.button() == mouse_button::button1) {
1142                 //theSelection().put(cur.grabSelection());
1143                 return;
1144         }
1145
1146         if (cmd.button() == mouse_button::button3) {
1147                 // try to dispatch to enclosed insets first
1148                 cur.bv().showDialog("mathpanel");
1149                 return;
1150         }
1151
1152         cur.undispatched();
1153 }
1154
1155
1156 bool InsetMathNest::interpret(LCursor & cur, char c)
1157 {
1158         //lyxerr << "interpret 2: '" << c << "'" << endl;
1159         string save_selection;
1160         if (c == '^' || c == '_')
1161                 save_selection = grabAndEraseSelection(cur);
1162
1163         cur.clearTargetX();
1164
1165         // handle macroMode
1166         if (cur.inMacroMode()) {
1167                 string name = cur.macroName();
1168
1169                 /// are we currently typing '#1' or '#2' or...?
1170                 if (name == "\\#") {
1171                         cur.backspace();
1172                         int n = c - '0';
1173                         if (n >= 1 && n <= 9)
1174                                 cur.insert(new MathMacroArgument(n));
1175                         return true;
1176                 }
1177
1178                 if (isalpha(c)) {
1179                         cur.activeMacro()->setName(name + c);
1180                         return true;
1181                 }
1182
1183                 // handle 'special char' macros
1184                 if (name == "\\") {
1185                         // remove the '\\'
1186                         if (c == '\\') {
1187                                 cur.backspace();
1188                                 if (currentMode() == InsetMath::TEXT_MODE)
1189                                         cur.niceInsert(createInsetMath("textbackslash"));
1190                                 else
1191                                         cur.niceInsert(createInsetMath("backslash"));
1192                         } else if (c == '{') {
1193                                 cur.backspace();
1194                                 cur.niceInsert(MathAtom(new InsetMathBrace));
1195                         } else if (c == '%') {
1196                                 cur.backspace();
1197                                 cur.niceInsert(MathAtom(new InsetMathComment));
1198                         } else if (c == '#') {
1199                                 BOOST_ASSERT(cur.activeMacro());
1200                                 cur.activeMacro()->setName(name + c);
1201                         } else {
1202                                 cur.backspace();
1203                                 cur.niceInsert(createInsetMath(string(1, c)));
1204                         }
1205                         return true;
1206                 }
1207
1208                 // One character big delimiters. The others are handled in
1209                 // the other interpret() method.
1210                 latexkeys const * l = in_word_set(name.substr(1));
1211                 if (name[0] == '\\' && l && l->inset == "big") {
1212                         string delim;
1213                         switch (c) {
1214                         case '{':
1215                                 delim = "\\{";
1216                                 break;
1217                         case '}':
1218                                 delim = "\\}";
1219                                 break;
1220                         default:
1221                                 delim = string(1, c);
1222                                 break;
1223                         }
1224                         if (InsetMathBig::isBigInsetDelim(delim)) {
1225                                 // name + delim ared a valid InsetMathBig.
1226                                 // We can't use cur.macroModeClose() because
1227                                 // it does not handle delim.
1228                                 InsetMathUnknown * p = cur.activeMacro();
1229                                 p->finalize();
1230                                 --cur.pos();
1231                                 cur.cell().erase(cur.pos());
1232                                 cur.plainInsert(MathAtom(
1233                                         new InsetMathBig(name.substr(1), delim)));
1234                                 return true;
1235                         }
1236                 }
1237
1238                 // leave macro mode and try again if necessary
1239                 cur.macroModeClose();
1240                 if (c == '{')
1241                         cur.niceInsert(MathAtom(new InsetMathBrace));
1242                 else if (c != ' ')
1243                         interpret(cur, c);
1244                 return true;
1245         }
1246
1247         // This is annoying as one has to press <space> far too often.
1248         // Disable it.
1249
1250 #if 0
1251                 // leave autocorrect mode if necessary
1252                 if (autocorrect() && c == ' ') {
1253                         autocorrect() = false;
1254                         return true;
1255                 }
1256 #endif
1257
1258         // just clear selection on pressing the space bar
1259         if (cur.selection() && c == ' ') {
1260                 cur.selection() = false;
1261                 return true;
1262         }
1263
1264         selClearOrDel(cur);
1265
1266         if (c == '\\') {
1267                 //lyxerr << "starting with macro" << endl;
1268                 cur.insert(MathAtom(new InsetMathUnknown("\\", false)));
1269                 return true;
1270         }
1271
1272         if (c == '\n') {
1273                 if (currentMode() == InsetMath::TEXT_MODE)
1274                         cur.insert(c);
1275                 return true;
1276         }
1277
1278         if (c == ' ') {
1279                 if (currentMode() == InsetMath::TEXT_MODE) {
1280                         // insert spaces in text mode,
1281                         // but suppress direct insertion of two spaces in a row
1282                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1283                         // it is better than nothing...
1284                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ')
1285                                 cur.insert(c);
1286                         return true;
1287                 }
1288                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1289                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1290                         return true;
1291                 }
1292                 if (cur.popRight())
1293                         return true;
1294                 // if are at the very end, leave the formula
1295                 return cur.pos() != cur.lastpos();
1296         }
1297
1298         // These shouldn't work in text mode:
1299         if (currentMode() != InsetMath::TEXT_MODE) {
1300                 if (c == '_') {
1301                         script(cur, false, save_selection);
1302                         return true;
1303                 }
1304                 if (c == '^') {
1305                         script(cur, true, save_selection);
1306                         return true;
1307                 }
1308                 if (c == '~') {
1309                         cur.niceInsert(createInsetMath("sim"));
1310                         return true;
1311                 }
1312         }
1313
1314         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1315             c == '%' || c == '_' || c == '^') {
1316                 cur.niceInsert(createInsetMath(string(1, c)));
1317                 return true;
1318         }
1319
1320
1321         // try auto-correction
1322         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1323         //      return true;
1324
1325         // no special circumstances, so insert the character without any fuss
1326         cur.insert(c);
1327         cur.autocorrect() = true;
1328         return true;
1329 }
1330
1331
1332 bool InsetMathNest::interpret(LCursor & cur, string const & str)
1333 {
1334         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1335         // possible
1336         if (!cur.empty() && cur.pos() > 0 &&
1337             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1338                 if (InsetMathBig::isBigInsetDelim(str)) {
1339                         string prev = asString(cur.cell()[cur.pos() - 1]);
1340                         if (prev[0] == '\\') {
1341                                 prev = prev.substr(1);
1342                                 latexkeys const * l = in_word_set(prev);
1343                                 if (l && l->inset == "big") {
1344                                         cur.cell()[cur.pos() - 1] =
1345                                                 MathAtom(new InsetMathBig(prev, str));
1346                                         return true;
1347                                 }
1348                         }
1349                 }
1350         }
1351         return false;
1352 }
1353
1354
1355 bool InsetMathNest::script(LCursor & cur, bool up, string const &
1356                 save_selection)
1357 {
1358         // Hack to get \^ and \_ working
1359         //lyxerr << "handling script: up: " << up << endl;
1360         if (cur.inMacroMode() && cur.macroName() == "\\") {
1361                 if (up)
1362                         cur.niceInsert(createInsetMath("mathcircumflex"));
1363                 else
1364                         interpret(cur, '_');
1365                 return true;
1366         }
1367
1368         cur.macroModeClose();
1369         if (asScriptInset() && cur.idx() == 0) {
1370                 // we are in a nucleus of a script inset, move to _our_ script
1371                 InsetMathScript * inset = asScriptInset();
1372                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1373                 inset->ensure(up);
1374                 cur.idx() = inset->idxOfScript(up);
1375                 cur.pos() = 0;
1376         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1377                 --cur.pos();
1378                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1379                 cur.push(*inset);
1380                 inset->ensure(up);
1381                 cur.idx() = inset->idxOfScript(up);
1382                 cur.pos() = cur.lastpos();
1383         } else {
1384                 // convert the thing to our left to a scriptinset or create a new
1385                 // one if in the very first position of the array
1386                 if (cur.pos() == 0) {
1387                         //lyxerr << "new scriptinset" << endl;
1388                         cur.insert(new InsetMathScript(up));
1389                 } else {
1390                         //lyxerr << "converting prev atom " << endl;
1391                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1392                 }
1393                 --cur.pos();
1394                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1395                 // special handling of {}-bases
1396                 // is this always correct?
1397                 if (inset->nuc().size() == 1
1398                     && inset->nuc().back()->asBraceInset())
1399                         inset->nuc() = inset->nuc().back()->asNestInset()->cell(0);
1400
1401                 cur.push(*inset);
1402                 cur.idx() = 1;
1403                 cur.pos() = 0;
1404         }
1405         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1406         cur.niceInsert(save_selection);
1407         cur.resetAnchor();
1408         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1409         return true;
1410 }