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