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