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