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