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