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