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