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